LoginSignup
11
17

More than 5 years have passed since last update.

json,jsonpとAjax通信のテンプレ

Last updated at Posted at 2016-02-20

jqXHR.success()、jqXHR.error()、jqXHR.complete()コールバックは、 jQury1.8で非推奨になりました。

ということで、jqXHR.done()、 jqXHR.fail()、jqXHR.always()を使用。

JSON

デモ:http://mo49.tokyo/qiita/20160220/method_json.html

javascript
$(document).ready(function(){

    //AJAX通信(ver1.8...)
    var request = $.ajax({
        type: 'POST',      //GET,POST
        data:{             //Dataプロパティはデータを送信(渡す)役目
            id: 1,
            mode: 'hoge',
            type: 'entry', 
            sleep: 0       //Timeoutテスト用
        },  
        url: "method_json.php",
        async:true,         //非同期=true・同期=false
        cache:false,        //初期値はtrueでキャッシュする状態
        dataType: 'json',   //text, html, xml, json, jsonp, script
        timeout: 3000
    });

    request.done(function(data, textStatus) {
        //パース処理
        var len = data.length;
        for(var i=0; i<len; i++){
           $("body").append('<p>'+data[i].id + '<br>' + data[i].mode+ '<br>' + data[i].type + '<br>' + data[i].date +'</p>');
        }
        $("#ajax_status").text("通信完了!");
    });

    request.fail(function(jqXHR, textStatus, errorThrown) {
            console.dir("----fail.----");
            console.dir("fail-jqXHR"+jqXHR);             //オブジェクト
            console.dir("fail-textStatus:"+textStatus);  //通信ステータス
            console.dir("fail-errorThrown"+errorThrown); //エラーメッセージ
    });

    request.always(function(data, textStatus) {
            console.dir("----always.----");  
            console.dir("always-data:"+data);              //データ
            console.dir("always-textStatus:"+textStatus);  //通信ステータス
    });

});
method_json.php
<?php
ini_set('mbstring.http_output', 'UTF-8');
ini_set('mbstring.internal_encoding', 'UTF-8');
//POSTパラメータを取得
$id = $_POST["id"];
$mode = $_POST["mode"];
$type = $_POST["type"];
$sleep = $_POST["sleep"];
$date = date("Y-m-d H-i-s");
sleep($sleep); //Timeoutテスト用
//受け取ったデータをjson形式で出力
$json = '[
    {
        "id":"'.$id.'",
        "mode":"'.$mode.'",
        "type":"'.$type.'",
        "date":"'.$date.'"
    }
]';
echo $json;

?>

JSONP

デモ:http://mo49.tokyo/qiita/20160220/method_jsonp.html

jsonpCallbackでコールバック関数を指定している点がポイント。

カルーセルにはslickを使用。

javascript
$(document).ready(function(){

    //AJAX通信(ver1.8...)
    var request = $.ajax({
        type: 'POST',      //GET,POST
        data:{             //Dataプロパティはデータを送信(渡す)役目
            sleep: 0      //Timeoutテスト用
        },  
        url: "method_jsonp.php",
        async:true,         //非同期=true・同期=false
        cache:false,        //初期値はtrueでキャッシュする状態
        dataType: 'jsonp',  //text, html, xml, json, jsonp, script
        jsonpCallback: 'jsonp_data', // callbackname jsonp側と合わせる
        timeout: 3000
    });

    request.done(function(data, textStatus) {
        // パース処理
        var len = data.length;
        for(var i=0; i<len; i++){
           $(".wrapper").append('<p class=".single-item"><img src="'+data[i].src + '" alt='+data[i].alt+'></p>');
        }

        //通信完了
        $("#ajax_status").text("通信完了!");
        $('.wrapper').slick({
            infinite: true,
            fade: true,
            cssEase: 'linear',
            autoplay:true,
            autoplaySpeed:1000,
            dots:true,
            pauseOnHover:true
        });
    });


    request.fail(function(jqXHR, textStatus, errorThrown) {
            console.dir("----fail.----");
            console.dir("fail-jqXHR"+jqXHR);             //オブジェクト
            console.dir("fail-textStatus:"+textStatus);  //通信ステータス
            console.dir("fail-errorThrown"+errorThrown); //エラーメッセージ
    });

    request.always(function(data, textStatus) {
            console.dir("----always.----");  
            console.dir("always-data:"+data);              //データ
            console.dir("always-textStatus:"+textStatus);  //通信ステータス
    });

});

method_json.php
<?php
ini_set('mbstring.http_output', 'UTF-8');
ini_set('mbstring.internal_encoding', 'UTF-8');
//POSTパラメータを取得
$sleep = $_POST["sleep"];
sleep($sleep); //Timeoutテスト用

$jsonp = '
jsonp_data(
[
    {
        "src":"img/1.png",
        "alt":"ルフィ"
    },
    {
        "src":"img/2.png",
        "alt":"ゾロ"
    },
        {
        "src":"img/3.png",
        "alt":"ナミ"
    },
     {
        "src":"img/4.png",
        "alt":"サンジ"
    }
]
);
';

echo $jsonp;

?>

参考
http://js.studio-kingdom.com/jquery/ajax/ajax

Deferred

非同期処理だから、以下を実行しても配列の中身は空。

var textAry = [];
var req = $.ajax({
    type: "GET",
    url: "../texts.txt",
    datatype: "text"
});
req.done(function(data){
    textAry = data.split('\n');
});
console.log(textAry);

async: false にすれば取得できるが、それではajaxの価値半減。
こういうときにDeferredを使うと良いのだろう。

参考
jQueryのDeferredが便利過ぎた

11
17
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
11
17