如何在 .getJSON jQuery 中设置编码
-
09-06-2019 - |
题
在我的网络应用程序中,我使用 jQuery 提交一些表单字段 $.getJSON()
方法。我在编码方面遇到一些问题。我的应用程序的字符集是 charset=ISO-8859-1
, ,但我认为这些字段是用 UTF-8
.
我如何设置使用的编码 $.getJSON
打电话?
解决方案
我认为你可能需要使用 $.ajax()
如果您想更改编码,请参阅 contentType
下面的参数( success
和 error
回调假设你有 <div id="success"></div>
和 <div id="error"></div>
在 HTML 中):
$.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);
}
});
实际上我大约一个小时前才必须这样做,真是巧合!
其他提示
如果你想使用 $.getJSON()
您可以在调用之前添加以下内容:
$.ajaxSetup({
scriptCharset: "utf-8",
contentType: "application/json; charset=utf-8"
});
您可以使用您想要的字符集来代替 utf-8
.
选项已解释 这里.
contentType :
向服务器发送数据时,使用此 content-type
. 。默认为 application/x-www-form-urlencoded
, ,这对于大多数情况来说都很好。
scriptCharset :
仅适用于请求 jsonp
或者 script
数据类型和 GET 类型。强制将请求解释为特定的字符集。仅当远程和本地内容之间的字符集差异时才需要。
您可能需要其中之一或两者...
您需要使用 Wireshark 分析 JSON 调用,以便查看是否在 JSON 页面的形成中包含字符集,例如:
- 如果页面很简单如果text/html
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
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;字符集 = ISO-8859-1");
这对我有用 无需将 JSON 传递的数据转换为 UTF-8,然后在页面上重新进行转换...
使用 encodeURI()
在客户端JS中并使用 URLDecoder.decode()
在服务器Java端工作。
例子:
JavaScript:
$.getJSON( url, { "user": encodeURI(JSON.stringify(user)) }, onSuccess );
爪哇:
java.net.URLDecoder.decode(params.user, "UTF-8");
使用此函数重新获得utf-8字符
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
例子:
var new_Str=decode_utf8(str);