【问题标题】:write a parsed response from a json file in a div在 div 中写入来自 json 文件的解析响应
【发布时间】:2015-08-26 21:57:16
【问题描述】:

假设我有一个这样的 json 文件:http://www.example.com/json?jsonp=parseRespond

我的 HTML 代码:

<script src="http://www.example.com/json?jsonp=parseRespond"></script>

http://www.example.com/json?jsonp=parseRespond回复是:

{"id":"5572a7d648b33a462d79145d","avatarHash":null,"bio":"","bioData":null,"confirmed":false,"fullName":"Ender Widgin","idPremOrgsAdmin":[],"initials":"EW","memberType":"normal"}

如何获取解析后的响应标头? 到目前为止,这是我尝试过的:

 var _request = undefined;
 var headers = _request.getResponseHeaders();
 document.write(headers);

但是,它不起作用!

注意:我没有执行 XMLHttpRequest,因为 Access-Control-Allow-Origin 不允许使用 Origin。

注意:我没有使用 callback=apiStatus,因为它重定向到未经授权的链接。

所以我可以获得响应的唯一方法是使用 jsonp=parseRespond 时,我如何在 div 中编写该响应?

【问题讨论】:

    标签: javascript ajax json http-headers xmlhttprequest


    【解决方案1】:

    由于您使用 JSONP 来处理从服务器接收到的数据,因此您需要编写自己的函数 parseRespond,该函数将该数据作为参数,并可能将其打印到您想要的特定 DIV。

    给定网址:

    http://www.example.com/s.json?jsonp=parseRespond
    

    您需要编写一个名为parseRespond 的函数,如下所示

    function parseRespond(data){
        // data is the response you received from that URL
        // e.g. data = {
        //     name: "John", 
        //     surname: "Conor",
        //     titles: ["Resistance Leader","Survivor"]
        // }
    
        // encapsulate, format or do something with the data here
        var output = data.name + " " + data.surname + " as " + data.titles.join(",");
    
        // Then print the output to your DIV like this example:
        $("#mydiv").html(output);
    }
    

    注意:JSONP 是带有回调的 JSON,您在 jsonp=func 中指定的术语会导致函数回调指向 func。您可能想阅读的更多信息在此线程中得到了很好的组织和讨论:

    What is JSONP all about?

    【讨论】:

    • 谢谢,但我收到的回复是这样的:{"id":"5572a7d648b33a462d79145d","avatarHash":null,"bio":"","bioData":null,"confirmed":false,"fullName":"Ender Widgin"}
    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多