【问题标题】:How can I parse JSON using the data parameter in JQuery?如何使用 JQuery 中的 data 参数解析 JSON?
【发布时间】:2015-07-29 03:34:34
【问题描述】:

我正在使用 Jersey 和 JQuery 为客户端制作一个 Web 应用程序。 我有以下返回 JSON 字符串的 URL:

http://localhost:8080/messenger/webapi/messages/1

返回:

 {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}

在浏览器中输入时。

现在我正在尝试使用以下 JQuery 函数在客户端获取此数据:

var rootURL = "http://localhost:8080/messenger/webapi/messages";

$(function() {


$('#btnRegister').click(function() {
    var username = $('#username').val();
    addMessage();
});

function addMessage() {

    var url = rootURL;
    $.ajax({
        type: 'GET',
        url: rootURL +"/1",
        dataType: "json", // data type of response
        success: (function(data) {
            var obj = jQuery.parseJSON(data);
            alert('ID: ' + obj.id);

        })
    });
}

});

编辑:当“btnRegister”被按下时,什么都不显示

这对我来说毫无意义。

【问题讨论】:

    标签: javascript jquery ajax json rest


    【解决方案1】:

    成功回调函数中有一些不需要的$ 包装,也不需要像设置dataType:'json' 那样解析响应。要更好地理解 $.ajax(),请阅读文档 here

    $(function() {
    
      $('#btnRegister').click(function() {
        var username = $('#username').val();
        addMessage();
      });
    
      function addMessage() {
    
        var url = rootURL;
        $.ajax({
          type: 'GET',
          url: rootURL + "/1",
          dataType: "json", // data type of response
          success: function(data) {
            //----^----------- remove the $ sign
            alert('ID: ' + data);
          }
        });
      }
    });

    您可以使用obj.propobj['prop'] 访问该值

    var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
    
    alert(obj.author);
    alert(obj['author']);

    【讨论】:

    • 好的,我已经做到了……正如我在编辑中指出的那样。现在什么都没有弹出? - 没关系!
    猜你喜欢
    • 2012-02-15
    • 2015-08-05
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多