Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - How to parse a JSON object from ajax call in Java Script

I am making an Ajax call in my JSP which is recieving a JSON response.

Running alert('Ajax Response ' + respArr); gives the following screen:

Screenshot of Alert message

The Java server-side code:

public void doGet(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
    try {
        String fromDate = request.getParameter("drFrom");
        String toDate = request.getParameter("drTo");
        JSONArray jsonArray = chartData.getCCSBJson(fromDate, toDate);
        res.setContentType("application/json");
        res.getWriter().write(jsonArray.toString());
    }

The JavaScript:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if(xmlhttp.responseText != null) {
        var respArr = xmlhttp.responseText;
        var jsonData = eval("(" + respArr + ")");
        alert('JSON Chart ' + jsonData); // The line from above
        var obj = JSON.parse(xmlhttp.responseText);
        alert('JSON Parse' + obj);

The JSON that is being returned:

[
  {
    "chart":{
      "caption":"",
      "exportDataFormattedVal":"1",
      "numberPrefix":"",
      "showexportdatamenuitem":"1",
      "xAxisName":"Bureau usage",
      "yAxisName":"count"
    },
    "data":[
      {
        "label":"SB AutoDecison",
        "value":"0"
      },
      {
        "label":"CC AutoDecison",
        "value":"0"
      },
      {
        "label":"CC Judgemental",
        "value":"0"
      },
      {
        "label":"SB Judgemental",
        "value":"0"
      }
    ]
  }
]

The alerts result:

alert('JSON Chart ' + jsonData) // JSON Chart[object Object]
alert('JSON Parse ' + obj);     // JSON parse[object Object]

What I want is to parse the object and generate an Excel sheet out of the content.

When I try to loop:

var jqueryData = jQuery.parseJSON(respArr);
var obj = JSON.parse(xmlhttp.responseText);
for (var i in obj) {
    alert('For loop string' + obj[i]);
}

It throws some 7 or 8 alerts with JavaScript code

for (i = 0; i < 5; i++) {
    alert(i + ' of respArr ' + respArr[i]);
}

Gives letter after letter of the JSON: [, {, ", c, h, and so on for each iteration of the loop.

Can I not just traverse the JSON like respArr[0].data or respArr[0].chart?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A couple of things:

First, your Java servlet is not really returning a "string". When you write jsonArray.toString(), yes, you are turning the array into a string, but that is solely for the purpose of writing it across the network. HTTP is a text protocol. So, what the doGet method is actually returning, in a sense, is a HTTP response (it just happens to be as text, it could very well be binary).

With that, when a client (in this case, your JavaScript via XMLHttpRequest) makes a GET request to your server (your servlet), it is getting back the JSON response (yes, as text). Your xmlhttp.responseText variable in this case should contain the JSON you've shown in the question.

Calling one of:

  • JSON.parse(xmlhttp.responseText)
  • jQuery.parseJSON(xmlhttp.responseText)
  • $.parseJSON(xmlhttp.responseText)

Should all return you the same object. With this object you can access its properties the way you want to. The following should work:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if (xmlhttp.responseText != null) {
        var json = xmlhttp.responseText;
        var arr = JSON.parse(json);
        var data = arr[0].data;       // This is what you want to do?
        var chart = arr[0].chart;     // This is what you want to do?
        // try running alert(chart.xAxisName);
        // and so on

Side note: When you run alert(obj); where obj is a object, you are seeing [object Object] because that is how JavaScript represents objects as strings. If you want to see the internals of a JavaScript object, as others have pointed out, you are better off using console.log(obj). (Also, upgrade or switch to a better browser. You will have access to better debugging tools.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...