jQueryのajax関数を利用してJSONPを扱う際にちょっとだけハマった。
jQueryのajax関数を利用してJSONPを扱う場合、dataTypeに「jsonp」を指定するだけではなく、「jsonpCallback」を使わないとparsererrorとかになる。
(ちなみに利用したjQueryのバージョンは1.8.2で、jsonpCallbackについては公式サイトの仕様に載っている)
以下はBasic認証配下に設置したPHPファイルが出力するJSONPのデータを取得したもの。
$.ajax({ url: 'https://json.data.domain/jsonp.php', type: 'POST', username: 'basic_auth_name', password: 'basic_auth_pw', data: {}, dataType : 'jsonp', jsonpCallback: 'callback', success: function(d) { console.log(d); }, error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + " " + textStatus); } });
こんな感じに、jsonCallbackにコールバック関数を指定してあげる。
ちなみにPHP側はこんな感じ
<?php $jsonArray = array( array( 'title' => 'テストデータ1タイトル', 'description' => 'テストデータ1概要', 'url' => 'http://www.google.com' ), array( 'title' => 'テストデータ2タイトル', 'description' => 'テストデータ2概要', 'url' => 'http://www.google.com' ), array( 'title' => 'テストデータ3タイトル', 'description' => 'テストデータ3概要', 'url' => 'http://www.google.com' ), array( 'title' => 'テストデータ4タイトル', 'description' => 'テストデータ4概要', 'url' => 'http://www.google.com' ), array( 'title' => 'テストデータ5タイトル', 'description' => 'テストデータ5概要', 'url' => 'http://www.google.com' ), ); header('Content-Type: text/javascript; charset=utf-8'); echo sprintf("callback(%s)",json_encode($jsonArray));