簡體   English   中英

JSONP-如何使用它?

[英]JSONP - How The Heck Do I Use It?

一直在嘗試制作一些JSONP來解決跨域問題。 這里使用的答案: 將.ajax()與JSONP一起使用的基本示例?

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

但是沒有得到理想的結果。 我的代碼:

jQuery的

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) . ")";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM