为什么我们要通过GET传递回调函数? 菜鸟在这里,我试过谷歌,它让我失望了。 据我了解,它可能看起来像这样(我不确定):
xhr.open("GET", "serverSideFile.php?callback=thisFunction", true);
帮助任何人?
这个想法是,如果请求返回 JSON 数据,则通过将请求放入 <script>
元素中来执行请求返回的 JS。
像....
// 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