Home > Web Front-end > JS Tutorial > body text

How to pass special character data in Ajax

php中世界最好的语言
Release: 2018-03-31 15:07:19
Original
1650 people have browsed it

This time I will show you how to pass special characters data in Ajax, and what are the precautions for passing special character data in Ajax. The following is a practical case, let’s take a look. take a look.

Problem Description

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

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

Unable to receive data 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");

Receive 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

I believe you have mastered the method after reading the case in this article, and there will be more exciting things Please pay attention to other related articles on php Chinese website!

Recommended reading:

How to implement AJAX paging effect

How to use Ajax to submit a form and receive the json data therein

The above is the detailed content of How to pass special character data in Ajax. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template