在我的Web应用程序中,我使用jQuery的$.getJSON()方法提交了一些表单字段。 我在编码方面遇到了一些问题。 我的应用程序的字符集是charset=ISO-8859-1,但是我认为这些字段是使用UTF-8提交的。
如何设置$.getJSON调用中使用的编码?
如果要使用$.getJSON(),可以在调用之前添加以下内容:
1 2 3 4
| $.ajaxSetup({
scriptCharset:"utf-8",
contentType:"application/json; charset=utf-8"
}); |
您可以使用所需的字符集代替utf-8。
这里说明了这些选项。
contentType :将数据发送到服务器时,请使用此content-type。默认值为application/x-www-form-urlencoded,在大多数情况下都可以。
scriptCharset :仅适用于具有jsonp或script dataType和GET类型的请求。强制将请求解释为某个字符集。仅需要用于远程内容和本地内容之间的字符集差异。
您可能需要一个或两个...
我认为,如果要更改编码,可能必须使用$.ajax(),请参见下面的contentType参数(success和error回调假定您在和 html):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| $.ajax({
type:"POST",
url:"SomePage.aspx/GetSomeObjects",
contentType:"application/json; charset=utf-8",
dataType:"json",
data:"{id: '" + someId +"'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
}); |
我实际上只需要大约一个小时前就完成了,真是巧合!
您需要使用Wireshark分析JSON调用,因此您将看到是否在JSON页面的构成中包含了字符集,例如:
1 2 3 4
| 0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK.
0010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content -Type: t
0020 65 78 74 2f 68 74 6d 6c 0d 0a 43 61 63 68 65 2d ext/html ..Cache-
0030 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 Control: no-cach |
-
如果页面的类型包括带有MIME" charset = ISO-8859-1"的自定义JSON
1 2 3 4 5 6
| 0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK.
0010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 .Cache-C ontrol:
0020 6e 6f 2d 63 61 63 68 65 0d 0a 43 6f 6e 74 65 6e no-cache ..Conten
0030 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d t-Type: text/htm
0040 6c 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 l; chars et=ISO-8
0050 38 35 39 2d 31 0d 0a 43 6f 6e 6e 65 63 74 69 6f 859-1..C onnectio |
这是为什么?因为我们不能将这样的目标放在JSON页面上:
就我而言,我使用制造商Connect Me 9210 Digi:
-
我必须使用一个标志来指示将使用非标准MIME:
p-> theCgiPtr-> = fDataType eRpDataTypeOther;
-
它在变量中添加了新的MIME:
strcpy(p-> theCgiPtr-> fOtherMimeType," text / html;
charset = ISO-8859-1");
它对我有用,而不必转换JSON传递的UTF-8数据,然后在页面上重做转换...
在客户端JS中使用encodeURI(),在服务器Java端工作中使用URLDecoder.decode()。
例:
使用此功能重新获得utf-8字符
1 2 3 4 5
| function decode_utf8(s) {
return decodeURIComponent(escape(s));
} |
例:
1
| var new_Str=decode_utf8(str); |