【问题标题】:Get JSON from ajax从ajax获取JSON
【发布时间】:2014-06-25 16:07:00
【问题描述】:

我正在使用 $.ajax 将数据发送到 servlet,但似乎所有数据都以符号 char 返回

var dataJson = {"title":"sss","message":"dddd","latLon":"(-30.410781790845874, 129.375)","address":"Maralinga SA 5710, Australia"} ;

$.ajax({
      url: 'http://mydomain/servler/call1',
      type: 'POST',                                     
      data:{
          data: JSON.stringify(datajson)
      },                                        
      dataType: 'json',
      success:function(results) {alert(results);
}
}); 


还有我的“call1”servlet

 response.setContentType("application/json");     

 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
 String json = "";
 json = br.readLine();
 log.info("Result Data json: " + json);

===> Result Data json:  %7B%22title%22%3A%22%22%2C%22message%22%3A%22%22%2C%22latLon%22%3A%22(-41.442726377672116%2C+143.26171875)%22%2C%22address%22%3A%22Oodnadatta+SA+5734%2C+Australia%22%7D

我不知道为什么我的 web 服务响应数据带有奇怪的数据....:|

【问题讨论】:

  • 如果你在谈论 % 的东西,这是在 HTTP 中编码字符的标准方法。

标签: jquery ajax jsf servlets


【解决方案1】:

当通过请求发送数据时,您的浏览器会将某些字符转换为其十六进制表示,并使用 % 符号进行转义。

如果你想用 Java 读取它,你需要对你得到的字符串进行解码。 java.net.URLDecoder.decode 包应该可以解决问题。

试试下面的代码:

response.setContentType("application/json");     

BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
json = java.net.URLDecoder.decode(br.readLine(), "UTF-8");
log.info("Result Data json: " + json);

【讨论】:

    【解决方案2】:

    谢谢安东尼奥,

    我的前任:

       String fileName = "Map%20of%20All%20projects.pdf";  
       fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
       System.out.print(fileName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2013-09-13
      • 2014-04-08
      相关资源
      最近更新 更多