帮助从服务器获得响应。有一个使用脚本标签以 JSONP 格式执行请求的功能
function call(a) {
alert(a);
}
function getJSONP(url, callback) {
// Create a unique callback name just for this request
var cbnum = "cb" + getJSONP.counter++; // Increment counter each time
var cbname = "getJSONP." + cbnum; // As a property of this function
if (url.indexOf("?") === -1) // URL doesn't already have a query section
url += "?jsonp=" + cbname; // add parameter as the query section
else // Otherwise,
url += "&jsonp=" + cbname; // add it as a new parameter.
var script = document.createElement("script");
getJSONP[cbnum] = function(response) {
try {
callback(response); // Handle the response data
}
finally { // Even if callback or response threw an error
delete getJSONP[cbnum]; // Delete this function
script.parentNode.removeChild(script); // Remove script
}
};
script.src = url; // Set script url
document.body.appendChild(script); // Add it to the document
}
getJSONP.counter = 0; // A counter we use to create unique callback names
getJSONP( "ph.php", call);
getJSONP( "http://my/ph.php", call);
这是 ph.php 本身,数据应该来自哪里作为响应
<?php
$seq = array("foo", "bar", "baz", "blong");
$json = json_encode($seq);
echo $json
但是浏览器显示错误: SyntaxError: expected expression, got '<'[More] ph.php:1 SyntaxError: expected expression, got '<'[更多]
关于语法错误,我已经在评论中写过了。我重复:
后跟
echo $json
一个分号jsonp
假设它不仅会返回json
,而且会被包裹在一个可以说是“信任”函数中。您不只是为 设置标识符callback
,而是说我将信任此请求并在它到达时立即执行它。结果,你需要在服务器上写:在这种情况下,答案将如下所示:
getJSONP.cb0(["foo","bar","baz","blong"])