【jQuery】ajax入門したので公式メモ
ページの一部更新やリクエストポーリングで使う技術
以前ハマったけど、分量も多くないしもっと早く公式読めば良かった
見たand役立った
Ajax | jQuery Learning Center
公式。これだけでok
コピペ用
- 基本
$.ajax({ url: "post.php", data: { name: "hisafi", id: 123 }, type: "GET", dataType : "json", timeout : 5000, }).done( (json) => { $( "<h1>" ).text( json.title ).appendTo( "body" ); $( "<div class=\"content\">").html( json.html ).appendTo( "body" ); }).fail( (xhr, status, errorThrown) => { alert( "Sorry, there was a problem!" ); console.log( "Error: " + errorThrown ); console.log( "Status: " + status ); console.dir( xhr ); }).always( (xhr, status) => { alert( "The request is complete!" ); });
- 基本 + 特定オプション指定
$.get( "/users.php", { userId: 1234 }, (resp) => { console.log( resp ); }); $.getJSON( "/details.php", (resp) => { $.each(resp, (key, value) => { console.log( key + " : " + value ); }); });
- jQueryオブジェクトへ読み込み結果を反映
$( "#newContent" ).load( "/foo.html" ); $( "#newContent" ).load( "/foo.html #myDiv h1:first", (html) => { alert( "Content updated!" ); });
便利そうなメソッド
- serialize() / serializeArray()
jQueryオブジェクトを クエリストリング / オブジェクトのアレイ 形式に変換してくれる
自分で値取得してdata組み立てしなくていいので活用したいところ