【问题标题】:Ajax content type Unicode issueAjax 内容类型 Unicode 问题
【发布时间】:2014-02-26 22:56:37
【问题描述】:

我们有一个字符串 česko 这是代码

$.ajax({
    type: 'GET',
    url: stringUrl,
    cache: false,
    contentType: 'application/json; charset=utf-8',
    success: function(response) {
        //on succes
    }
});

当我们通过查询字符串时,我们在 javascript 中收到相同的字符串

但是当我们将上面提到的字符串传递给 web api 控制器时

然后我们在 C# 代码中收到 ?esko 字符串,而不是 česko 字符串。

请帮忙

【问题讨论】:

  • 问题已使用此方法解决 var uri = "my test.asp?name=ståle&car=saab"; var res = encodeURI(uri);

标签: c# javascript ajax unicode


【解决方案1】:

根据你的评论,你真的应该改变:

var uri = "my test.asp?name=ståle&car=saab"; var res = encodeURI(uri);

到这样的事情:

var fileName = "my test.asp";
// You can join the string literals I have below together, but I am
//   splitting them apart here for the sake of the discussion below.
var res = fileName + "?" + "name" + "=" + encodeURIComponent("ståle") +
            "&" + "car" + "=" + encodeURIComponent("saab");

我上面的代码假设变量 namesnamecarfileName 一样仅是 ASCII。如果您的 fileName 中可能有非 ASCII 字符,则应在其上使用 encodeURI(因为它不应该有“?”字符来开始查询字符串),而如果变量 names 像 "name" 和 "car" 实际上有非 ASCII 字符,您应该在它们上使用 encodeURIComponent(但不要在我的代码中包含的 "?"、"&" 和 "=" 字符上使用)。

在非 ASCII 部分需要 encodeURIComponent() 的原因是,这将确保诸如“=”、“&”和“?”之类的字符。被转义而不是被允许拆分您的查询字符串。

【讨论】:

    猜你喜欢
    • 2011-08-01
    • 2016-06-15
    • 2017-01-16
    • 2011-06-04
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 2018-03-01
    • 2018-08-16
    相关资源
    最近更新 更多