【问题标题】:Making an HTTP GET request to a REST API endpoint向 REST API 端点发出 HTTP GET 请求
【发布时间】:2017-05-05 17:13:37
【问题描述】:

https://api.iflychat.com/users/list/demo/c-g 发出 HTTP GET 请求

以上 URL 以 JSON 格式返回网站上的在线用户列表。结果数组中的每个条目都有以下属性(最后一个除外):

• u – 用户 ID

• n – 用户名

• s – 用户的状态

• p – 用户的个人资料 URL

结果数组的最后一个元素表示列表中的用户总数。

我想在我的网络应用程序中呈现这个列表并每分钟更新一次数据。

var $Form = $('form'), $Container = $('#container');
$Container.hide();
$Form.on('submit', function(p_oEvent){
var sUrl, oData;
p_oEvent.preventDefault();
sUrl = 'https://api.iflychat.com/users/list/demo/c-g'
$.ajax(sUrl, {
    complete: function(p_oXHR, p_sStatus){
        oData = $.parseJSON(p_oXHR.responseText);
        console.log(oData);
        alert(oData);
        $Container.find('.userId').text(oData.u);
        $Container.find('.name').text(oData.n);
        $Container.find('.image').html('<img src="' + oData.p + '"/>');
        $Container.find('.status').text(oData.s);
        $Container.show();
    }
 });    
});

这是我当前的 JavaScript 代码。HTML 页面上有一个提交按钮。我是通过 REST API 解析 json 的新手,请帮助我将列表解析为对象数组。并且该列表应每 1 分钟更新一次。

【问题讨论】:

  • 您有问题吗?
  • @Quentin 对不起!请再次查看问题。
  • 无需手动解析。只需将响应正文放入 JSON.parse() 即可。详情见这里:developer.mozilla.org/de/docs/Web/JavaScript/Reference/…
  • 您需要提供minimal reproducible example 和正确的问题描述。假设 JSON 由一组对象组成,那么 oData = $.parseJSON(p_oXHR.responseText); 已经可以满足您的要求。如果不是,那么您需要向我们展示一个将p_oXHR.responseText 替换为硬编码样本值的测试用例,告诉我们您解析后oData 的值是什么,并告诉我们您的预期它是。
  • @Tobi — 他们已经在使用 $.parseJSON,这是一个包装器(具有真正过时浏览器的兼容层)。

标签: javascript json ajax http-get


【解决方案1】:

我将您的代码简化为基本问题,您的 API 似乎返回了“应用程序/json”内容,该内容已被 jQuery 解析为对象数组。请在下面找到一个工作示例,该示例还将检查数据是否为字符串,然后将其解析为对象。请注意,您可能会添加一些错误处理,以防 API 返回字符串格式的错误而不是有效的 JSON。

编辑:添加了 setInterval。

function getCurrentUserList(){
  sUrl = 'https://api.iflychat.com/users/list/demo/c-g'
  $.get(sUrl, function(data, status){
    console.log("status:", status);
    var oData;
    if(typeof(data) === "string"){
      //just in case the result is not already of type 'object'
      //TODO: needs error handling
      oData = JSON.parse(data);
    }else{
      //this is what should happen in most cases for the given API
      oData = data;
    }
  
    //display data form the second entry:
    console.log(oData[1].n);
    console.log(oData[1].s); 
    console.log(oData[1].p);   
  });
}

//get data now
getCurrentUserList();

//get data every 5 seconds:
setInterval(getCurrentUserList,5000);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 2021-10-05
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多