前一阵子使用JQuery Ajax做的一个注册表单需要传送中文字符给WebService,发送的是”GET”请求,发过去后在WebService这边看到的都是乱码,摸索了一阵子,找到了如下的解决方案:

var data = {
     UserName: escape(your user name here),
     Password: escape(your password here),
};

var jsonStr = JSON.stringify(data);  // the json2 method.

$.ajax({
     url: '../Service.asmx/Login',
     data: 'userinfo=' + jsonStr,
     contentType: "application/json; charset=utf-8",
     dataType: "jsonp",
     type: "GET",
     success: function(response) {
          …
     },
     error: function(a, b, c) {
          …
     }
});

这个方案就是使用javascript的escape方法来对中文字符进行编码,然后到WebService那里会自动解码成为中文。
今天又碰到了另外一个问题:用JQuery Ajax GET传送瑞典字符等Unicode字符出现乱码,即便是用了escape也无济于事。
思考: 通过GET方法发送的请求实际上还是通过URI来传送参数的,那么GET方式传送的字符就与文件设定的编码格式无关了,完全是由URI来决定传送的是什么,那么如果对URI进行编码呢?
事实上,javascript已经有这样的全局函数来实现对URI的编码了:encodeURI(uri),让JQuery Ajax发送一个由URI编码好的数据就不会出现乱码了,而且在WebService端还能自动对数据进行decode.
改善后的代码如下:

var data = {
     UserName: encodeURI(your user name here),
     Password: encodeURI(your password here),
};

var jsonStr = JSON.stringify(data);  // the json2 method.

$.ajax({
     url: '../Service.asmx/Login',
     data: 'userinfo=' + jsonStr,
     contentType: "application/json; charset=utf-8",
     dataType: "jsonp",
     type: "GET",
     success: function(response) {
          …
     },
     error: function(a, b, c) {
          …
     }
});

这个改进后的方案不仅仅对中文字符有效,而且对其他的Unicode字符都可以有效的解决乱码问题。

相关文章:

  1. How to use Sql Azure
  2. 性能: 字符串倒序算法 (C# version)
  3. 在.NET项目中使用log4net
  4. The online doc/spreadsheet/present service by G.o.o.g.l.e
  5. 网络第一美人思翻唱倒带
  6. Update the application configuration file automatically in C#
  7. I still didn’t take actions.
  8. I am experiencing more from my surround.
  9. 【视频】2010年最清纯网络美女 奶茶MM
  10. 恶搞QQ好友印象