0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ajax,JSON

0
Posted at

非同期通信とは

通常HTTPを使って、データ通信を行います。クライアントからリクエストを送ったときに(リクエスト)中は、新たにリクエストを送ることはできません。そこで、Ajaxを使うことで、リクエストを出してから、レスポンスを受け取るまでに処理を完了することができます。ページ変移をすることなく処理を実行することができます。
Javascript側がWebサービスにリクエストを送り、返されてきたデータもJS自身が受け取るという流れです。したがって、ページを変移するというユーザーへのストレスがないのがメリットです。

Ajaxの記述方法

index.js
$.ajax ({url : "データのURL", data_type: "json"})

urlには、ダウンロードしたいURL。date_typeにはjsonを追加します。

公式のページがわかりやすかった。

index.js
$(document).ready(function() {
    //ファイルの読み込み
    $.ajax({url: 'data.json', dataType: 'json'})
    .done(function(data) {
        data.forEach(function(item, index) {
            if(item.crowded === 'yes') {
                const idName = '#' + item.id;
                $(idName).find('.check').addClass('crowded');
            }
        });
    })
    .fail(function(){
        window.alert('読み込みエラー');
    });

    //クリックされたら空き席状況を表示
    $('.check').on('click', function() {
        if($(this).hasClass('crowded')) {
            $(this).text('残席わずか').addClass('red');
        } else {
            $(this).text('お席あります').addClass('green');
        }
    });
});

ダウンローされたデータ(ajax)は関数(data)に保存されます。データが保存された後の処理に移ります。
dataの中には、JSONデータが入っています。

data.json
[
    {"id":"js","crowded":"yes"},
    {"id":"security","crowded":"no"},
    {"id":"aiux","crowded":"no"}
]

この中身は、1つの配列の中に、3つのオブジェクトがあります。
これら、配列の内容を呼び出すには、forEachメソッドを使用します。
コンソールに出力するために、呼び出します。

JSONとは

ざっくり行ってしまうと、配列とオブジェクトの融合ですね。
配列のように[]で囲まれていますね。更に、オブジェクトのように{}で囲まれています。
このJSONデータの中身は、3つの配列で成り立っていて、中身は、2つのプロパティのオブジェクトで成り立っています。
すべての値をダブルクオーテーションで囲む形になっています。

要素にクラス属性を追加する

関数内のitemにはJSONのオブジェクトが入っています。

ここからif文での条件分岐を行います。
trueになったときに、定数 idNameにid名文字列を代入します。(#js)

index.js
$('セレクタ<idName>').find('.check').取得した要素<addClass>.('クラス名<crowded>')

取得した要素にクラスがあるかどうかを調べる

index.js
$('セレクタ名<this>').hashClass('クラス名<crowded>')

確かな力が身につくJavaScript「超」入門 第2版

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?