如何访问JSON对象的值?

时间:2016-03-02 06:36:34

标签: jquery json ajax

我正在返回一个json,如下所示

o / p of console.log(obj.roles);

[Object, Object, suggest: function, vanquish: function]
0: Object
        jnl_id: "2"
        jnl_journal_name: "About Origin of speci"
        role_id: "5"
        role_name: "Technical Head"
        usr_id: "7"
        usr_username: "dd"
        usrj_jnl_id: "2"
        usrj_usr_id: "7"
        __proto__: Object
1: Object
        jnl_id: "2"
        jnl_journal_name: "About Origin of speci"
        role_id: "10"
        role_name: "EBM - Reviewer"
        usr_id: "7"
        usr_username: "dd"
        usrj_jnl_id: "2"
        usrj_usr_id: "7"
        __proto__: Object
        length: 2
        __proto__: Array[0]

ajax函数是datatype : json

success:function (data) {                   
    obj = $.parseJSON(data);

    if(obj.status == "success"){
        console.log(obj.roles);

        $.each(obj.roles, function (index, value) {

            console.log(value.roles_id);//output undefined
            $("#journal_user_role").append($("<option>", {
                value: value.roles_id,
                text: value.roles
            }));
            $("#journal_user_role").trigger("chosen:updated");
        });
    }
}

我想找到role_idrole_name并附加一个多选框。

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var data = {
	"status": "success",
	"roles": [{
		"role_name": "Technical Head",
		"role_id": "5",
		"usr_username": "dd",
		"jnl_journal_name": "About Origin of speci",
		"usrj_usr_id": "7",
		"usrj_jnl_id": "2",
		"usr_id": "7",
		"jnl_id": "2"
	}, {
		"role_name": "EBM - Reviewer",
		"role_id": "10",
		"usr_username": "dd",
		"jnl_journal_name": "About Origin of speci",
		"usrj_usr_id": "7",
		"usrj_jnl_id": "2",
		"usr_id": "7",
		"jnl_id": "2"
	}]
};
var dataroles = data.roles;
console.log("status: " + data.status);
for(var i = 0 ; i < dataroles.length; i++){
  
  console.log("role_id "+ i +": "+ dataroles[i].role_id);
  console.log("role_name "+ i +": "+ dataroles[i].role_name);
  }
&#13;
&#13;
&#13;

试试这个

答案 1 :(得分:0)

尝试使用 value ['roles_id'] 而不是 value.roles_id .....