如何显示从 jQuery .ajax 帖子返回的 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16821847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:52:15  来源:igfitidea点击:

How to display returned JSON from a jQuery .ajax post

jqueryjsonparsingstring-parsing

提问by Dirty Bird Design

Starting to work on a project that is built completely on JSON data. It is returned like this:

开始着手一个完全基于 JSON 数据构建的项目。它是这样返回的:

{"location":{"id":10,"contactPhone":"8675309","contactName":"bob","name":"bill smith","zipCode":"90210","state":"California","address1":"104 S. Olive","city":"Temecula","country":"USA"},"success":true}

I am comfortable processing data returned in HTML form (usually tables) by traversing the DOM with the .find and other filtering to find success flags. I have no idea how to do this with JSON - I need to filter to the last object "success" and check if it is true or false. With HTML returned data I do it like this:

通过使用 .find 和其他过滤器遍历 DOM 来查找成功标志,我可以轻松地处理以 HTML 形式(通常是表格)返回的数据。我不知道如何用 JSON 做到这一点 - 我需要过滤到最后一个对象“成功”并检查它是对还是错。使用 HTML 返回的数据,我这样做:

submitHandler: function(form) {
    $.ajax({
     //other ajax stuff
      success: function(data) {
        var answer = $(data).find("td:eq(1)").text();
        var message = $(data).find("td:eq(3)").text();
        //console.log(data);
        if (answer == "True") {
          $('#messages').show().html(message);
      } else {
          $('#messages').show().html('Error logging in: ' + message);
      }
    }
  });
  return false;
  }
  1. Even after using this method I don't completely understand what the function(data) means, Ive used data, msg and responsewithout really understanding what the difference between them are.
  1. 即使在使用这种方法之后,我也没有完全理解函数(数据)的含义,我使用了数据、消息和响应,但没有真正理解它们之间的区别。

I am able to post to the webservice and get the returned JSON with this .ajax call

我可以发布到网络服务并通过这个 .ajax 调用获取返回的 JSON

$.fn.serializeObject = function() {....}
submitHandler: function(form){
    var wrapper = {};
    var location = {};
    wrapper.location = $("#newLocation").serializeObject();
        $.ajax({
            type: $(form).attr('method'),
            url: '/web/service/' + 'locationService' + '/' + 'createLocation',
            dataType: 'json',
            async: false,
            data: JSON.stringify(wrapper),
            success: function(msg) {
                    console.log('success' + msg );
                    //need to traverse to success and if true, do something
            },
                    error: function(msg) {
                    console.log('failure' + msg );
                    //need to traverse to success and if false, do something
            }
    });
    return false;
}
  1. How do you filter to the "success" part in a JSON string (string or object?)
  2. What are the correct terms for the key/number pairs (is that even correct) in the JSON string IE "contactPhone":"8675309"
  3. How do you then display the data if "success":"true" - I will work on that myself but if anyone has good method I would appreciate some advice. I would imagine you just appendTo a table somehow?

    I have a lot of questions on JSON, and am trying to word the questions in a general manner so that the help I am given can help someone else, I apologize for the length of this post. I appreciate any help and if requested will shorten/edit this question.

  1. 如何过滤到 JSON 字符串(字符串或对象?)中的“成功”部分
  2. JSON 字符串 IE“ contactPhone”:“ 8675309”中键/数字对的正确术语是什么(甚至正确)
  3. 如果“成功”:“真”,你如何显示数据 - 我会自己处理,但如果有人有好的方法,我会很感激一些建议。我想你只是以某种方式附加到一个表?

    我有很多关于 JSON 的问题,我试图用一般的方式来表达这些问题,以便我得到的帮助可以帮助其他人,我为这篇文章的长度道歉。我感谢任何帮助,如果需要,将缩短/编辑这个问题。

采纳答案by A. Wolff

msg here is a json formatted object. You can get success value like that:

这里的 msg 是一个 json 格式的对象。你可以获得这样的成功价值:

success: function(msg) {
                    console.log('success' + msg.success );
                    if(msg.success) { //could be wrote: msg.success === true
                        //do some stuff
                    }
            },

"contactPhone":"8675309"

“联系电话”:“8675309”

contactPhone is the key, "8675309" is the value. But in your sample, to get "contactPhone" value, you need to first get the location object:

contactPhone 是键,“8675309”是值。但是在您的示例中,要获取“contactPhone”值,您需要先获取位置对象:

var contactPhoneValue = msg.location.contactPhone;

回答by TaLha Khan

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. http://www.json.org/

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。人类很容易阅读和写作。机器很容易解析和生成。 http://www.json.org/

Now the code for reading and writing properties of json object is very similar as it is for normal javascript object.

现在用于读取和写入 json 对象属性的代码与普通 javascript 对象非常相似。

$ajax({
  dataType:'json',
  success:function(data){
        console.log(data['success']);   //returns for whatever will be the value for succes
        //or
        console.log(data.success);   //returns for whatever will be the value for succes
        data.location['contactName'] = "new name";                    
 }
});

Accessing and manipulating javascript and Json object is same.
Here is a very good guide for them:
http://www.dyn-web.com/tutorials/obj_lit.php

访问和操作 javascript 和 Json 对象是一样的。
这是他们的一个很好的指南:http:
//www.dyn-web.com/tutorials/obj_lit.php



UPDATED:
A better version, maybe this could help:
http://jsfiddle.net/hvzcg/4/



更新:
一个更好的版本,也许这可以帮助:http:
//jsfiddle.net/hvzcg/4/