javascript - Javascript/jquery ajax 请求
问题描述
我有这个 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);
}
解决方案
在来自服务器端的 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...});
推荐阅读
- ruby-on-rails - 编辑对象 Modal Ruby on Rails
- java - 没有这样的列: UserPhone (code 1): ,编译时: DELETE FROM OrderDetail WHERE UserPhone='+59175223813'
- html - 如何使用 CSS 充分利用图像进行响应式布局?
- matlab - 如何使这个 for 循环更有效?
- bash - MacOS:.bashrc 的奇怪行为;不运行评论,似乎在解析中删除字符
- perl - 如何使用 pmcmd 命令行在 PERL 环境中捕获 PowerCenter 工作流的成功/失败状态?
- java - 使用内部类的 JDBI
- python - 如何在给定字符之后删除字符串中的字符?
- python - 为什么我们在使用 tensorboard 时需要 add_graph() 的第二个参数?
- reactjs - 如何在 React Native 中删除 react-native-tts 异步函数的事件监听器