簡體   English   中英

如何在GET請求中將回調函數作為參數傳遞?

[英]How does one pass a callback function as a parameter in the GET request?

為什么我們要通過GET傳遞回調函數? Noob在這里,而我嘗試了google,但失敗了。 據我了解,它可能看起來像這樣(我不確定):

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

暫無
暫無

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

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