How to solve the problem of Ajax passing data with special characters

亚连
Release: 2018-05-22 11:33:23
Original
1479 people have browsed it

This article introduces you to the solution when the data passed by Ajax contains special characters. Friends who need it can refer to it

Problem description

As follows, the text containing special characters is encapsulated in JSON and passed through Ajax.

var data = {"Id": id, "text": text};

In Data reception cannot be performed in the background.

Solution

Replace

req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Copy after login

with:

req.setRequestHeader("Content-type", "application/json; charset=utf-8");
Copy after login

Accept data in the background:

//进行json数据的接收 StringBuilder sb = new StringBuilder(); BufferedReader br = request.getReader(); char[] buff = new char[10000]; int len; while((len = br.read(buff)) != -1){ sb.append(buff, 0, len); } String mess = sb.toString(); //将字符串转换为JSON对象 JSONObject jsonObject=new JSONObject(mess); //获取其中的值 jsonObject.getInt("Id"); //含有特殊字符的文本需要先进行转码 URLDecoder.decode(jsonObject.getString("text"), "UTF-8"));
Copy after login

In this way, you can receive the text correctly~

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Configuring Chrome to support local (file protocol) AJAX requests (graphic tutorial)

The AJAX paging effect is simple Implementation (graphic tutorial)

Json-lib processing solution when using frameworks such as Ajax or Easyui (graphic tutorial)

The above is the detailed content of How to solve the problem of Ajax passing data with special characters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!