首页 > 解决方案 > 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);

}

标签: javascriptphpjquery

解决方案


在来自服务器端的 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...});

推荐阅读