我正在发出jsonp请求,但我收到此错误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.
,尽管请求返回了200代码。
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);
?>
答案 0 :(得分:0)
在PHP中,在echo
之前设置header('Content-Type: application/json');
你的PHP没有任何回调(你没有返回JSONP)。你希望它看起来像..
echo $_GET['callback'].'('.json_encode($arr).')';
我错过了绝对的明显。 JSONP用于跨站点AJAX调用。您将其用作脚本。
这是加载数据的一种非常尴尬的方式。通常的方法是通过脚本中的AJAX调用加载数据,而不是全局加载变量。
如果您真的想要使用您的设计,请保留application / json标记但返回原始echo json_encode($arr);
您还可以删除?callback =&#39;回调&#39; - 它什么也没做。
答案 1 :(得分:0)
您需要强制指定输出类型。 尝试添加
header('Content-Type: application/json');
在test.php
然后你需要将整个编码输出包装成一个回调名称,以便客户端的js可以使用它:
$callbackName = filter_input(INPUT_GET, 'callback');
echo $callbackName . '(' . json_encode($arr) . ')';