通过 JavaScript 遍历/解析 JSON 对象 [英] Iterating through/Parsing JSON Object via JavaScript

查看:35
本文介绍了通过 JavaScript 遍历/解析 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 jQuery/Ajax/JSON 时遇到问题.我正在使用像这样的 jQuery ajax 帖子......

$.ajax({类型:POST",数据类型:json",网址:someurl.com",数据:"cmd="+escape(me.cmd)+"&q="+q+"&"+me.args,成功:函数(objJSON){呜呜呜……}});

据我所知,这将返回一个 JavaScript JSON 对象?ajax 帖子产生的文本是这样的(我相信这是有效的 JSON)...

<代码>{学生":{身份证":456,"full_name": "GOOBER, ANGELA","user_id": "2733245678",斯廷":2733212346"},学生":{身份证":123,"full_name": "鲍勃,史蒂夫","user_id": "abc213",斯廷":9040923411"}}

我似乎无法弄清楚如何解析 jQuery ajax 帖子返回的 JSON 对象......基本上我想循环并从每个返回的学生中制作一个 div......

$("

" + student.full_name + " (" + student.user_id + " - " + student.stin + ")

")

我似乎无法弄清楚如何去做...

谢谢!

解决方案

您的 JSON 对象不正确,因为它有多个同名的属性.您应该返回一组学生"对象.

<预><代码>[{身份证":456,"full_name": "GOOBER ANGELA","user_id": "2733245678",斯廷":2733212346"},{身份证":123,"full_name": "鲍勃,史蒂夫","user_id": "abc213",斯廷":9040923411"}]

然后你可以这样迭代它:

 for (var i = 0, len = objJSON.length; i < len; ++i) {var 学生 = objJSON[i];$("

" + student.full_name + " (" + student.user_id + " - " + student.stin + ")</div>")...}

I'm having a problem with jQuery/Ajax/JSON. I'm using a jQuery ajax post like so...

$.ajax({
  type: "POST",
  dataType: "json",
  url: "someurl.com",
  data: "cmd="+escape(me.cmd)+"&q="+q+"&"+me.args,
  success: function(objJSON){
    blah blah...
  }
});

It's my understanding that this will return a JavaScript JSON object? The text that the ajax post produces is this (I believe this is valid JSON)...

{
  "student":{
    "id": 456,
    "full_name": "GOOBER, ANGELA",
    "user_id": "2733245678",
    "stin": "2733212346"
  },
  "student":{
    "id": 123,
    "full_name": "BOB, STEVE",
    "user_id": "abc213",
    "stin": "9040923411"
  }
}

I can't seem to figure out how to parse through the JSON object returned by the jQuery ajax post... basically I want to loop through and make a div out of each student returned like so...

$("<div id="" + student.id + "">" + student.full_name + " (" + student.user_id + " - " + student.stin + ")</div>")

I just can't seem to figure out how to do it...

Thanks!

解决方案

Your JSON object is incorrect because it has multiple properties with the same name. You should be returning an array of "student" objects.

[
   {
     "id": 456,
     "full_name": "GOOBER ANGELA",
     "user_id": "2733245678",
     "stin": "2733212346"
   },
   {
     "id": 123,
     "full_name": "BOB, STEVE",
     "user_id": "abc213",
     "stin": "9040923411"
   }
]

Then you can iterate over it as so:

 for (var i = 0, len = objJSON.length; i < len; ++i) {
     var student = objJSON[i];
     $("<div id="" + student.id + "">" + student.full_name + " (" + student.user_id + " - " + student.stin + ")</div>")...
 }

这篇关于通过 JavaScript 遍历/解析 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆