如何从服务器发送JSON数组客户端,即(Java来AJAX / JavaScript)的?数组、客户端、服务器、JSON

2023-09-10 21:25:52 作者:笑我太深情

我在JSON.java文件中的以下JSON数组:

I have the following JSON array in my JSON.java file:

ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");

我想送阵列位于AJAX.jsp的AJAX脚本。 我知道如何通过例如

I would like to send array to the AJAX script located in AJAX.jsp. I know how to receive the text in AJAX via e.g.

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

但我不知道如何从服务器发送数组到客户端! 鸭preciate你的帮助

But I don't know how to send the array from the server to the client! Appreciate your help

推荐答案

确定第一:

ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");
JSONArray array = new JSONArray();

这不能编译...你有一个重复的变量数组; - )

This can't compile... you have a duplicate variable array ;-)

二:创建一个servlet / Struts的Action /等即会包含code,它将创建数组。然后将其转换以JSON用JSON库。最后,将字符串在servlet / Struts的Action /等的响应。

Second: create a servlet/Struts Action/etc that will contains the code that will create your array. Then transform it in JSON with a JSON library. Finally, put the string in the response of your servlet/Struts Action/etc.

使用jQuery来缓解你的Ajax调用的努力。它会帮助你的Ajax调用和HTTP响应接收到的字符串转换回JSON。

Use JQuery to ease your effort on the Ajax call. It will help you with the Ajax call and the transformation back to Json from the string received in the http response.

例如:

你的Ajax调用应该是这样的(使用jQuery)

your ajax call should be like that (with JQuery)

$.getJSON("http://yourserver/JSONServlet",
    function(data){
           alert (data) // this will show your actual json array
      });
    });

和你的servlet应该看起来像:

and your servlet should look like that:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.JSONArray;

public class JSONServlet extends  HttpServlet{
  public void doGet(HttpServletRequest request,
  HttpServletResponse response)
   throws ServletException,IOException{
 JSONArray arrayObj=new JSONArray();
 arrayObj.add("D");
 arrayObj.add("A");
 arrayObj.add("L");
 arrayObj.add("D");
 arrayObj.add("A");
 arrayObj.add("TEST");
  PrintWriter out = response.getWriter();
  out.println(arrayObj);
  for(int i=0;i<arrayObj.size();i++){
  out.println(arrayObj.getString(i));
  }
 }
}