我对这个Ajax请求有一个问题,它会在调用过程中导致错误,它不会在控制台和编译器中显示。
Javascript code:
jQuery(document).ready(function(){
jQuery.get({
url: "https://nonsoloalimentatori.it/tools/download-center/index.php?sku="+sku,
dataType: "jsonp",
cache: true,
success: function(){
console.log("success");
},
error: function(){
console.log("error");
}
}).done(function(){
console.log("here");
})
})PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials:');
header('Content-Type: application/json');
function searchJson($sku){
$array = [];
$json = file_get_contents('./list.json'); //read the file contente
$json_data = json_decode($json,true); //creating the json objectt
$n_elementi = count($json_data); //count the number of object element
for ($mul = 0; $mul < $n_elementi; ++$mul){ //for every element it is
searched the sku
if($json_data[$mul]["sku"] == $sku)//and it is compared to the sku
given by user
{
array_push($array,$json_data[$mul]);//if it is true the element
is added to array
}
}
return $array; //it is returned
}
if(isset($_GET['sku'])){
$result=searchJson($_GET['sku']);
echo json_encode($result, JSON_PRETTY_PRINT);
}发布于 2018-06-26 04:23:50
对于来自服务器端的jsonp响应,jquery希望它在回调函数下。
请使用以下代码输出服务器响应:
$callback_function_name = !empty($_GET['callback'])? $_GET['callback'] : 'callback';
echo $callback_function_name.'('.json_encode($result, JSON_PRETTY_PRINT).')';回调函数的原因是:在javascript中不允许跨域ajax调用,因此在jsonp中,url的加载方式与我们加载js脚本文件的方式相同(您可以在站点中添加来自不同域的脚本)。然后对加载的脚本进行求值。如果打印普通数据,则不执行任何操作。因此它被传递给调用方JS注册的回调函数进行处理。
您也可以通过在函数中设置: ajax jsonp:"custom_callback_function_name"作为参数来设置您自己的回调函数。在这种情况下,您的服务器端输出应该如下所示:
custom_callback_function_name({...json_data...});https://stackoverflow.com/questions/51025374
复制相似问题