简体   繁体   English

如何在JavaScript中打印JSON响应

[英]How to print JSON response in javascript

I am able to make a Ajax request and getting response as well in form of JSON string, still alert box of JavaScript is not showing actual response text. 我能够以JSON字符串的形式发出Ajax请求并获得响应,但是JavaScript的警告框仍未显示实际响应文本。 I am new to ajax concept and dont know much. 我是ajax概念的新手,并不了解很多。

Ajax-Call:- Ajax的电话: -

Action triggered on dropdown
<select name="state" onchange="getOptions(this.value)">

Javascript Function called :-
function getOptions(state){
  AJAX.onreadystatechange = handler;
  AJAX.open("GET", "getData?id="+state);
  AJAX.send();
};

Response Firebug is showing 响应Firebug正在显示

回应内容

This is my code to fetch response and print. 这是我的代码,用于获取响应和打印。

function handler() {
  if(AJAX.readyState == 4 && AJAX.status == 200) {
    var json = eval('(' + AJAX.responseText +')');
    alert('Success. Result:' + json);
  }
  else if (AJAX.readyState == 4 && AJAX.status != 200) {
      alert('Something went wrong...');
  }
}

Every time its a success but i get output as 每次成功,但我都会得到输出 在此处输入图片说明

You need to treat your response as JSON not as text. 您需要将响应视为JSON而不是文本。

Try this: 尝试这个:

function handler() {
    if (AJAX.readyState == 4 && AJAX.status == 200) {
        var json = JSON.parse(AJAX.responseText), len = json.length, i = 0, txt = "";
        for (; i < len; i++) {
            if (txt) {
                txt += ", ";
            }
            txt += json[i].name;
        }
        alert('Success. Result:' + txt);
    } else if (AJAX.readyState == 4 && AJAX.status != 200) {
        alert('Something went wrong...');
    }
}

If you need to see the value as part of debugging the code, you should use console.log(AJAX) to inspect the value. 如果需要在调试代码时看到该值,则应使用console.log(AJAX)检查该值。

If you really need to display some message to the user, then reconsider showing the json result unformatted/filtered - that said you could iterate through all the objects properties and concenate theese in a string (like @Hiral shows). 如果您确实需要向用户显示一些消息,请重新考虑显示未格式化/过滤的json结果-表示您可以遍历所有对象的属性,并在字符串中合并theese(例如@Hiral显示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM