【问题标题】:How does one pass a callback function as a parameter in the GET request?如何在 GET 请求中将回调函数作为参数传递?
【发布时间】:2013-09-18 15:28:15
【问题描述】:

为什么我们要通过 GET 传递回调函数?菜鸟在这里,我试过谷歌,但它让我失望了。据我了解,它可能看起来像这样(我不确定):

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

帮助任何人?

【问题讨论】:

    标签: javascript php ajax http callback


    【解决方案1】:

    这个想法是,如果请求返回 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

    【讨论】:

    • myCallback 是如何被调用的?它会因为它是 URL 的一部分而被自动调用吗?或者我需要打电话吗?编辑:措辞
    • so... 1. 请求在查询字符串中包含回调 2. 服务将返回的 json 包装在回调的函数调用中。 3.客户端js获取响应并注入到脚本标签中。 4.浏览器执行这段代码调用回调函数
    • 谢谢!我想事情对我来说越来越清楚了。另外,作为澄清,我希望服务在其返回字符串中添加“myCallback”,对吗?
    • 所以我想,我的问题是......服务器端代码的编码器应该解析我的 GET 请求并查找我的回调函数的名称,然后使用该名称来包装json数据? (我很困惑,包装是默认的服务器行为还是编码人员遵循的更多政策/礼仪。)
    • 是的,正如你所说。所以如果要返回的数据是数字3,那么就需要返回为myCallback(3)
    猜你喜欢
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多