1

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?

3 Answers 3

3

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

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

0
0

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.