虽然它在那里,但无法直接访问ajax响应属性

时间:2013-03-27 09:44:14

标签: javascript jquery ajax json

我有从PHP 5.3.10的json_encode函数返回到jQuery 1.9.1的以下JSON字符串

{
   "messsages":{
      "error":["API_CONTROLLER.INVALID_LOGIN_PASSWORD"],
      "warning":[],
      "notice":[],
      "success":[]
   },
   "result":false
}

jQuery代码:

$.ajax(targetURL, {
   type: method,
   data: params,
   dataType: "json",
   success: function(resp){
      console.log(resp); //Shows object with all vars correctly displayed

      //The for loop also outputs all keys and values correctly
      for(var i in resp){
         console.log("I: "+i);
         console.log("RESP: ");
         console.log(resp[i]);
      }

      console.log("DIRECT ACCESS");
      console.log(resp.messages); //WHY undefined?
      //console.log(resp.messages[error]); //undefined
      //console.log(resp.messages[error][0]); //undefined
      //console.log(resp.messages.error); //undefined
      //console.log(resp.messages.length); //Just trying => undefined
      console.log(resp.result); //this works!
      //console.log(resp[messages]); //Just trying => undefined
   }
});

如何访问消息?

第一个console.log和循环显示消息存在,还有messages.error,messages.notice等等。但是我怎样才能访问它们?这种jQuery错误吗?

2 个答案:

答案 0 :(得分:4)

你的回复的消息var中有三个's'。因此它在循环中有效,但在您尝试访问未发送的“消息”时失败。

答案 1 :(得分:1)

首先解决拼写错误(消息)然后您可以稍微重写代码:)

在Google Chrome中使用JavaScript Developer Tools

{
   "messages":{
      "error":["API_CONTROLLER.INVALID_LOGIN_PASSWORD"],
      "warning":[],
      "notice":[],
      "success":[]
   },
   "result":false
}

The jQuery code:

var performLogin = function(){
 return $.getJSON(targetURL, params).done(function(response){

      // TODO - do something with response

      console.log(response.messages);
      console.log(response.messages[error]);
      console.log(response.messages[error][0]);
      console.log(response.messages.error);
      console.log(response.messages.length);
      console.log(response.result);
      console.log(response[messages]);
   });
}