Home > Web Front-end > Front-end Q&A > What to do if jquery ajax parameters pass garbled characters

What to do if jquery ajax parameters pass garbled characters

PHPz
Release: 2023-04-05 14:23:23
Original
726 people have browsed it

With the development of Internet technology, more and more websites use Ajax technology to achieve dynamic interaction on web pages. jQuery, the most popular JavaScript library, is also the first choice for many websites. However, when using jQuery's Ajax to send POST requests, many developers will encounter a very embarrassing problem - garbled Chinese parameters. This article will talk about the causes and solutions to this problem.

Cause of the problem

When sending a POST request, jQuery's Ajax method serializes the parameters in the "application/x-www-form-urlencoded" format by default and sends them to the backend. This format is relatively simple and has the best compatibility among browsers. However, when the parameters contain Chinese characters, it will cause garbled characters. This is because this format does not support Chinese, and Chinese requires URL encoding and escape for correct transmission.

In order to solve this problem, we can consider using another data format provided by jQuery - "multipart/form-data". This format supports Chinese, but it should be noted that when using this format, the request header will contain "Content-Type: multipart/form-data; boundary=----XXXXXX", which will cause the browser to automatically Adds a delimiter that might interfere with the backend parsing the parameter value.

Solution

In response to the above problems, we can use the following three solutions:

Method 1: Manually encode the URL

When transmitting parameters , we can manually encode the URL and then decode it on the backend. Parameters can be encoded using JavaScript's encodeURIComponent() method. For example:

$.ajax({
  type:'POST',
  url:url,
  data: {'name':encodeURIComponent('张三'),'age':20},
  success:function(data){
    console.log(data);
  }
});
Copy after login

In the backend, use Java's URLDecoder.decode() method to decode:

String name = URLDecoder.decode(request.getParameter("name"), "UTF-8");
int age = Integer.parseInt(request.getParameter("age"));
Copy after login

This method is more troublesome and requires encoding and decoding operations on both the front and back ends.

Method 2: Modify the request header

We can modify the request header, change "Content-Type" to "application/json;charset=utf-8", and use JSON format to transmit data. For example:

$.ajax({
  type:'POST',
  url:url,
  contentType: "application/json;charset=utf-8",
  data: JSON.stringify({'name':'张三','age':20}),
  success:function(data){
    console.log(data);
  }
});
Copy after login

In the backend, use Java's JsonParser to parse JSON:

JsonParser parser = new JsonParser();
JsonObject object = parser.parse(json).getAsJsonObject();
String name = object.get("name").getAsString();
int age = object.get("age").getAsInt();
Copy after login

This method is relatively simple, but it is only suitable for transmitting data in JSON format.

Method 3: Modify the backend code

If the backend uses PHP, you can directly use $_POST or $_REQUEST to obtain the parameter value, without encoding and decoding. For example:

$name = isset($_POST['name']) ? $_POST['name'] : '';
$age = isset($_POST['age']) ? intval($_POST['age']) : 0;
Copy after login

If the backend uses Java, you can use the getInputStream() method of HttpServletRequest to obtain the parameter value. For example:

StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = null;
try {
  InputStream inputStream = request.getInputStream();
  bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  String line = null;
  while((line = bufferedReader.readLine()) != null) {
    sb.append(line);
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if(bufferedReader != null) {
    try {
      bufferedReader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
Copy after login

Next, we can use JsonParser to parse data in JSON format, or manually parse data in application/x-www-form-urlencoded format.

In short, each method has its own advantages and disadvantages, and we can choose the method that suits us best according to the specific situation. No matter which method is used, you need to pay attention to the encoding and decoding of Chinese parameters to avoid garbled characters.

The above is the detailed content of What to do if jquery ajax parameters pass garbled characters. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template