简体   繁体   中英

How to send an array from Servlet to Java Script with AJAX?

I need send an array to js with ajax, this is my function with ajax in a java script...

$.ajax({
    url: "/localizacion/ServletPeticiones",
    type:"Post",
    data:"accion=LatLong_UR",
    dataType: "text",
    success: function(results){
        console.info(results);
        cad=results;   
    }
    });

I've got an array String[][] datos , and I have to send this array from my Servlet to JS with the last function.

How I can do this? How receive the array from my Servlet with my function of ajax in a js?

The servlet will return a application/json response, and a JSON-encoded array (better, you can use a Map<String, String> ). There are libraries, like Gson , to do the conversion:

public void doPost(HttpServletRequest request, HttpServletResponse response) {
  response.setContentType("application/json; charset=UTF-8");

  Gson gson = new Gson();
  Map<String, String> datos = getDatos(); // you have to implement this

  response.getWriter().println(gson.toJson(datos));
}

You can try using JSON .. you can use google's GSON library to convert an array into JSON representation and send it to your client

On the client side ... change the $.ajax's dataType to "json"

In the success function you just use the returned data as javascript array

JSON would be the right way to go about it. PHP has json_encode function that very well does it for you from arrays. Another way is to manually create a JSON string although it's not a good idea. On the other hand, just for practice and get familiar with JSON, it's advisable, but you are better of using built-in json generating capabilities of your server side platform.

You might want to send a correct header from the server so browsers are able to receive it as json data: " Content-Type: application/json "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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