【发布时间】:2013-09-18 15:28:15
【问题描述】:
为什么我们要通过 GET 传递回调函数?菜鸟在这里,我试过谷歌,但它让我失望了。据我了解,它可能看起来像这样(我不确定):
xhr.open("GET", "serverSideFile.php?callback=thisFunction", true);
帮助任何人?
【问题讨论】:
标签: javascript php ajax http callback
为什么我们要通过 GET 传递回调函数?菜鸟在这里,我试过谷歌,但它让我失望了。据我了解,它可能看起来像这样(我不确定):
xhr.open("GET", "serverSideFile.php?callback=thisFunction", true);
帮助任何人?
【问题讨论】:
标签: javascript php ajax http callback
这个想法是,如果请求返回 JSON 数据,则执行请求返回的 JS,方法是将其放入 <script> 元素中。
类似......
// the request stuffs
var xhr = new XMLHttpRequest();
// detect state changes
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) { // this is completed state
// build the script element to inject into
var s = document.createElement("script");
s.type = "text/javascript";
// put the ajax response into the script element
s.innerHTML = xhr.responseText;
// add it to the <HEAD>
document.getElementByTagName("head")[0].appendChild(s);
}
}
xhr.open("GET", "serverSideFile.php?callback=myCallback", true);
xhr.send(null); // do that ajax
// the callback function
function myCallback(data) {
// do blah
}
服务的回报将是……
myCallback([{title: "item1", value: "blah1"},{title: "item2", value: "blah2"}]);
编辑:
我猜你也可以在这个上使用 HTML5 脚本异步,只是......
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = "serverSideFile.php?callback=myCallback";
document.getElementByTagName("head")[0].appendChild(s);
编辑: 这是一篇关于它的文章:http://en.wikipedia.org/wiki/JSONP
【讨论】:
3,那么就需要返回为myCallback(3)。