如何从Java脚本中的Ajax调用解析JSON对象 [英] How to parse a JSON object from ajax call in Java Script

查看:132
本文介绍了如何从Java脚本中的Ajax调用解析JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在JSP中进行Ajax调用,该调用正在接收JSON响应.

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

运行alert('Ajax Response ' + respArr);会显示以下屏幕:

Java服务器端代码:

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());
    }

JavaScript:

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);

正在返回的JSON:

[
  {
    "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"
      }
    ]
  }
]

警报结果:

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

我想要的是解析对象并从内容中生成Excel工作表.

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

当我尝试循环播放时:

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

它使用JavaScript代码引发大约7或8条警报

It throws some 7 or 8 alerts with JavaScript code

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

在循环的每次迭代中,依次给出JSON字母:[{"ch等.

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

我能不能像respArr[0].datarespArr[0].chart那样遍历JSON?

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

推荐答案

以下几点:

首先,您的Java Servlet并未真正返回字符串".是的,当您写入jsonArray.toString()时,您正在将数组转换为字符串,但这仅是为了通过网络写入它. HTTP是文本协议.因此,从某种意义上讲,doGet方法实际上返回的是HTTP响应(它恰好是文本形式,很可能是二进制形式).

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).

这样,当客户端(在这种情况下,您的JavaScript通过XMLHttpRequest)向服务器(您的servlet)发出GET请求时,它将返回JSON响应(是,作为文本).在这种情况下,您的xmlhttp.responseText变量应该包含问题中显示的JSON.

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.

呼叫以下其中之一:

  • JSON.parse(xmlhttp.responseText)
  • jQuery.parseJSON(xmlhttp.responseText)
  • $.parseJSON(xmlhttp.responseText)
  • 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

旁注:当运行alert(obj);(其中obj是对象)时,会看到[object Object],因为这是JavaScript将对象表示为字符串的方式.正如其他人指出的那样,如果您想查看JavaScript对象的内部结构,最好使用console.log(obj). (此外,升级或切换到更好的浏览器.您将可以使用更好的调试工具.)

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.)

这篇关于如何从Java脚本中的Ajax调用解析JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆