简体   繁体   English

如何使用AJAX将数组从Servlet发送到Java Script?

[英]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将数组发送到js,这是我在java脚本中使用ajax的函数...

$.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. 我有一个数组String[][] datos ,我必须使用最后一个函数将这个数组从我的Servlet发送到JS。

How I can do this? 我怎么能这样做? How receive the array from my Servlet with my function of ajax in a js? 如何通过js中的ajax函数从我的Servlet接收数组?

The servlet will return a application/json response, and a JSON-encoded array (better, you can use a Map<String, String> ). servlet将返回一个application/json响应和一个JSON编码的数组(更好的是,你可以使用Map<String, String> )。 There are libraries, like Gson , to do the conversion: Gson这样的库可以进行转换:

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 您可以尝试使用JSON ..您可以使用谷歌的GSON库将数组转换为JSON表示并将其发送到您的客户端

On the client side ... change the $.ajax's dataType to "json" 在客户端...将$ .ajax的dataType更改为“json”

In the success function you just use the returned data as javascript array 在success函数中,您只需将返回的数据用作javascript数组

JSON would be the right way to go about it. JSON将是正确的方法。 PHP has json_encode function that very well does it for you from arrays. PHP有json_encode函数,它可以很好地为您提供数组。 Another way is to manually create a JSON string although it's not a good idea. 另一种方法是手动创建一个JSON字符串,虽然这不是一个好主意。 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. 另一方面,只是为了练习并熟悉JSON,这是可取的,但你最好使用服务器端平台的内置json生成功能。

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 " 您可能希望从服务器发送正确的标头,以便浏览器能够以json数据的形式接收它:“ Content-Type: application/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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