繁体   English   中英

如何在 .getJSON jQuery 中设置编码

[英]How to set encoding in .getJSON jQuery

在我的 Web 应用程序中,我使用 jQuery 的$.getJSON()方法提交了一些表单字段。 我在编码方面遇到了一些问题。 我的应用程序的charset=ISO-8859-1charset=ISO-8859-1 ,但我认为这些字段是用UTF-8提交的。

如何设置$.getJSON调用中使用的编码?

如果你想使用$.getJSON()你可以在调用之前添加以下内容:

$.ajaxSetup({
    scriptCharset: "utf-8",
    contentType: "application/json; charset=utf-8"
});

您可以使用您想要的字符集而不是utf-8

此处解释这些选项。

contentType :向服务器发送数据时,使用此content-type 默认为application/x-www-form-urlencoded ,这对大多数情况来说都很好。

scriptCharset :仅适用于具有jsonpscript数据类型和 GET 类型的请求。 强制将请求解释为某个字符集。 仅需要远程和本地内容之间的字符集差异。

您可能需要一种或两种...

我认为如果您想更改编码,您可能必须使用$.ajax() ,请参阅下面的contentType参数( successerror回调假设您有<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);
    }
});

实际上,大约一个小时前我不得不这样做,真是太巧了!

您需要使用 Wireshark 分析 JSON 调用,因此您将查看是否在 JSON 页面的格式中包含字符集,例如:

  • 如果页面很简单 if 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; charset = ISO-8859-1 ");

它对我有用,而无需将 JSON 传递的数据转换为 UTF-8,然后在页面上重做转换......

在客户端 JS 中使用encodeURI()并在服务器 Java 端工作中使用URLDecoder.decode()


例子:

  • 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);

如果你想使用 $.getJSON() 你可以在调用之前添加以下内容:

$.ajaxSetup({
    scriptCharset: "utf-8",
    contentType: "application/json; charset=utf-8"
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM