クロスサイト 許可なし(JSONP)

JSONP【JSON with Padding】のデータタイプを利用することにより、CORS Policy 違反を回避することができます。

PRAjax コンストラクタの第3引数に true を指定することで JSONP の Ajax 通信となります。

なお、JSONP はその仕組み上 GET しかできないため、POST を指定しても GET で送信されます。


サンプルでは、GET(JSON) は同一オリジンポリシー違反でエラー(Access to XMLHttpRequest at 'https://dodat.jp/samples/pr_ajax/samples/12/response.php' from origin 'https://app.softwarenote.info' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.)となります。

GET(JSONP) と POST(JSONP) は両方とも GET の通信になります。

Script Source
var data = {"name_inputText1":"テキスト1", "name_textArea1":"テキスト2"};
var url = "https://dodat.jp/samples/pr_ajax/samples/12/response.php";

// get (JSON)
var getAjax = new PRAjax(url, "get");
getAjax.onClick("#id_button", data);

// get (JSONP)
var getAjax2 = new PRAjax(url, "get", true);
getAjax2.onClick("#id_btnGET", data);

// post (JSONP)
var postAjax = new PRAjax(url, "post", true);
postAjax.onClick("#id_btnPOST", data);

response.php
$vals = array();
$vals['inputText1'] = $_REQUEST['name_inputText1'];
$vals['textArea1'] = $_REQUEST['name_textArea1'];

$res = array();
$res['vals'] = $vals;
$response = json_encode($res, JSON_UNESCAPED_UNICODE);
print $response;