0

そして、なぜ GET を介してコールバック関数を渡すのでしょうか? Noob ここで、Google を試してみましたが、失敗しました。私が理解していることから、それは次のように見えるかもしれません(そして私にはわかりません):

xhr.open("GET", "serverSideFile.php?callback=thisFunction", true);

誰か助けて?

4

1 に答える 1

1

<script>リクエストがJSONデータを要素に入れることによって返された場合、リクエストによって返された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

于 2013-09-18T15:41:54.270 に答える