从$ .ajax的成功函数中读取对象

嗨,我有遵循ajax功能..

         $.ajax({
                url: './sales/cat/salesCat'
              , target: null
              , type: "get"
              , dataType: "json"
              , data: {

                  locale: LOCALE
              }
              , success: function (object) {
                  $.each(object, function (key, value) {
                      alert(key + ":" + value);
                  })
              }
         });

它返回以下输出

 {
  "success": true,
  "totalCount": 2,
  "data": [
    {
      "East Division": "Yearly Sales"
      "West Division": "Yearly Sales"
    }
  ]
}

问题是我正在尝试读取返回的值以使用它。 当Success函数执行时,在我的警报中,我收到警报消息

         data:[object Object]

请让我知道如何纠正

          $.each(object, function (key, value) {
                  alert(key + ":" + value);
              })

因此警报可以显示例如East Division:Yearly Sales感谢您的帮助。

采纳答案:

那是因为当使用alert()输出对象时,对象被转换为字符串。 作为字符串的对象是“[object Object]”。

相反,您应该使用console.log()将对象输出到浏览器的JavaScript控制台

var data = { key: "value" };
data.toString(); // "[object Object]"
data; // Object { key: "value" }

您遇到的另一个问题是您的data响应缺少a ,因此无效:

"data": [
    {
      "East Division": "Yearly Sales" // <--- No comma
      "West Division": "Yearly Sales"
    }
]

这将抛出:

SyntaxError:意外的令牌:


参考更多解答: Reading object from success function of $.ajax ,转载请保留出处从$ .ajax的成功函数中读取对象及作者信息

Statement: We respect knowledge and authors. Since the content comes from the Internet and is intended for scientific research, any reprinters should retain the author's signature and origin. If you are the author of the content and feel in dispute, please contact email: 1076545519@qq.com. We will find out the situation and deal with it in time. We sincerely thank the author for his hard work.


更多:javascript