0

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

{
   "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错误吗?

4

2 回答 2

4

您的回复的消息变量名称中有三个“s”。因此它在循环中有效,但在您尝试访问不存在的“消息”时失败。

于 2013-03-27T09:47:09.193 回答
1

首先修复错字(消息)然后你可以重写你的代码:)

使用Google Chrome 中的JavaScript 开发人员工具

{
   "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]);
   });
}
于 2013-03-27T09:59:36.263 回答