ajax前后端传值乱码

var searchText = "英语";
    //通过URL传递:需要编码两次
    searchText = encodeURI(searchText);
    searchText = encodeURI(searchText);
    $.ajax({
        type: 'GET',
        url: 'search.action' + "?searchText=" + searchText,
        data: '',
        contentType: 'text/json,charset=utf-8',
        dataType: 'json',
        success: function (data) {
        }
    });
1
2
3
4
5
6
7
8
9
10
11
12
13
    var searchText = "英语";
    //通过ajax数据传递:只需编码一次~
    searchText = encodeURI(searchText);
    $.ajax({
        type: 'GET',
        url: 'search.action',
        data: {searchText:searchText},
        contentType: 'text/json,charset=utf-8',
        dataType: 'json',
        success: function (data) {
        }
    });
1
2
3
4
5
6
7
8
9
10
11
12
后端接收中文数据:

//都只要反编码一次就行了
queryCon=URLDecoder.decode(queryCon,"utf-8");
1
2
后端返回带中文的json数据:

//只需对中文的内容进行编码,如果对整个json字符串进行编码,json中的“”等字符也会被编码导致前端解析json错误
URLEncoder.encode("中文内容","utf-8");
1
2
前端解析带中文的json数据:

    $.ajax({
        type: 'GET',
        url: 'search.action',
        data: {searchText:searchText},
        contentType: 'text/json,charset=utf-8',
        dataType: 'json',
        success: function (data) {
            //对应的也只需要对中文进行反编码,例如data.name是中文内容
            alert(decodeURI(data.name));
        }
    });
1
2
3
4
5
6
7
8
9
10
11
前端的一些编码方法:

<script type="text/javascript">
    //escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。比如"春节"的返回结果是%u6625%u8282,escape()不对"+"编码 主要用于汉字编码。
    alert(escape("春节"));
    alert(unescape(escape("春节")));
    //encodeURI()是用来对URL编码的函数。 编码整个url地址,但对特殊含义的符号"; / ? : @ & = + $ , #"不进行编码。对应的解码函数是:decodeURI()。
    alert(encodeURI('http://baidu.com?hello=您好&word=文档'));
    alert(decodeURI(encodeURI('http://baidu.com?hello=您好&word=文档')));
    //encodeURIComponent() 能编码"; / ? : @ & = + $ , #"这些特殊字符。对应的解码函数是decodeURIComponent()。
    alert(encodeURIComponent('http://baidu.com?hello=您好&word=文档'));
    alert(decodeURIComponent(encodeURIComponent('http://baidu.com?hello=您好&word=文档')));
</script>

1
2
3
4
5
6
7
8
9
10
11
12
总结:
escape:已经废弃,不推荐使用!!!,而且无法对“/”编码,服务器会报错
encodeURIComponent:传递参数时需要使用encodeURIComponent,推荐使用
encodeURI:用来对请求的URL编码的,不是对请求的参数编码。
--------------------- 
作者:诚o 
来源:优快云 
原文:https://blog.youkuaiyun.com/qq_22771739/article/details/81564042 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值