gpt4 book ai didi

javascript - JSONP——我到底要怎么使用它?

转载 作者:行者123 更新时间:2023-11-30 16:56:29 25 4
gpt4 key购买 nike

一直在尝试编写一些 JSONP 来解决跨域问题。此处使用的答案:Basic example of using .ajax() with JSONP?

$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});

但没有得到想要的结果。我的代码:

j查询

var url = "http://wplivestats.com/stats/jsonp.php?callback=?";

$.getJSON(url, function(result){
//response data are now in the result variable
console.log(result);
});

PHP

<?php 

include('init.php');
$pubid = $_REQUEST['pid'];

date_default_timezone_set ( 'America/New_York' );

$time = date('Y-m-d H:i:s',time()-$polling_minutes*60);
$count = $conn->prepare("select distinct ip from stats where timestamp >= '$time' AND Pubid = '$pubid'");
$count->execute();
$users['users'] = $count->rowCount();
echo "jsonCallback ( [";
echo json_encode($users);
echo "] )";
?>

错误:

ReferenceError: jsonCallback is not defined
jsonCallback ( [{"users":0}] )

我哪里错了?

最佳答案

问题出在您的 PHP 脚本中。当您使用 jQuery 发出请求时,url 中的问号将替换为动态函数名称。

在 PHP 端,您需要使用此动态函数名称来包装您的数据,而不是使用“jsonCallback”。

您的 PHP 代码应如下所示:

echo $_GET['callback'] . "(" . json_encode($users) . ")";

关于javascript - JSONP——我到底要怎么使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com