拒绝在 jsonp 请求上执行脚本
Refused to execute script on jsonp request
我正在发出 jsonp 请求,尽管请求 returns 一个 200 代码,但我收到此错误 Refused to execute script from 'https://myurl/test.php?callback=%27callback%27' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
。
function callback(response){
alert(response);
}
var script = document.createElement("script");
//Set the Type.
script.type = "text/javascript";
//Set the source to the URL the JSON Service.
script.src = "https://myurl/test.php?callback='callback'";
//Append the script element to the HEAD section.
document.getElementsByTagName("head")[0].appendChild(script);
这是test.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
在PHP,回显前设置
header('Content-Type: application/json');
并且您的 PHP 没有任何回调(您没有返回 JSONP)。你想让它看起来像..
echo $_GET['callback'].'('.json_encode($arr).')';
已编辑
我错过了绝对明显的。 JSONP 用于跨站点 AJAX 调用。您正在将其用作脚本。
这是一种非常笨拙的数据加载方式。通常的方法是通过脚本中的 AJAX 调用加载数据,而不是全局加载变量。
如果你真的想继续你的设计,保留 application/json 标签但回到你原来的 echo json_encode($arr);
你也可以删除 ?callback='callback' -- 它什么都不做。
您需要强制指定输出类型。
尝试添加
header('Content-Type: application/json');
在test.php
中输出数组之前
然后您需要将整个编码输出包装到回调名称,以便 client-side 上的 js 可以使用它:
$callbackName = filter_input(INPUT_GET, 'callback');
echo $callbackName . '(' . json_encode($arr) . ')';
我正在发出 jsonp 请求,尽管请求 returns 一个 200 代码,但我收到此错误 Refused to execute script from 'https://myurl/test.php?callback=%27callback%27' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
。
function callback(response){
alert(response);
}
var script = document.createElement("script");
//Set the Type.
script.type = "text/javascript";
//Set the source to the URL the JSON Service.
script.src = "https://myurl/test.php?callback='callback'";
//Append the script element to the HEAD section.
document.getElementsByTagName("head")[0].appendChild(script);
这是test.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
在PHP,回显前设置
header('Content-Type: application/json');
并且您的 PHP 没有任何回调(您没有返回 JSONP)。你想让它看起来像..
echo $_GET['callback'].'('.json_encode($arr).')';
已编辑
我错过了绝对明显的。 JSONP 用于跨站点 AJAX 调用。您正在将其用作脚本。
这是一种非常笨拙的数据加载方式。通常的方法是通过脚本中的 AJAX 调用加载数据,而不是全局加载变量。
如果你真的想继续你的设计,保留 application/json 标签但回到你原来的 echo json_encode($arr);
你也可以删除 ?callback='callback' -- 它什么都不做。
您需要强制指定输出类型。 尝试添加
header('Content-Type: application/json');
在test.php
然后您需要将整个编码输出包装到回调名称,以便 client-side 上的 js 可以使用它:
$callbackName = filter_input(INPUT_GET, 'callback');
echo $callbackName . '(' . json_encode($arr) . ')';