Url 编码 javascript 对象字面量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11054078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:56:58  来源:igfitidea点击:

Url Encode javascript object literal

javascriptjqueryajaxasp.net-mvc-3url

提问by JayAr

I have Model

我有模型

public class SomeModel
{
    public string SomeText { get; set; }
}

In javascript I make an javascript object literal of the model:

在 javascript 中,我创建了一个模型的 javascript 对象文字:

var model = {
                SomeText: "test"
            };
var serializedData = JSON.stringify(model);

This makes a string which looks like the following:

这将生成一个如下所示的字符串:

"{"SomeText":"test"}"

Now suppose I want to send this model to a controller which accepts a model like this with the following function:

现在假设我想将此模型发送到一个控制器,该控制器接受具有以下功能的模型:

public void Index(SomeModel model)
{
}

What I need is an url string in which the model has the following form:

我需要的是一个 url 字符串,其中模型具有以下形式:

"?SomeText=test"

I know that ajax does exactly this when you send the model via ajax post:

我知道当您通过 ajax post 发送模型时,ajax 就是这样做的:

$.ajax({type:"POST", 
        url: "someUrl", 
        data: serializedData,
        ...
});

The 'data:' url-encodes the serialized data.

'data:' url 对序列化数据进行编码。

But I actually do not want to use ajax, so I need to build this url myself. I want to do exactly the same thing as ajax does with 'data:'. How can I url-encode the serialized data myself?

但是我实际上不想使用ajax,所以我需要自己构建这个url。我想做与 ajax 对“数据:”所做的完全相同的事情。如何自己对序列化数据进行 url 编码?

回答by zzzzBov

You should use jQuery.param:

你应该使用jQuery.param

$.param({foo:'bar', fizz:'buzz'});
//produces foo=bar&fizz=buzz


Arrays are ok too:

数组也可以:

$.param({foo:['bar', 'baz']});
//produces foo%5B%5D=bar&foo%5B%5D=baz
//which is the url encoded form of: foo[]=bar&foo[]=baz

if you need the traditional array syntax, use the second parameter:

如果您需要传统的数组语法,请使用第二个参数:

$.param({foo:['bar','baz']}, true);
//produces foo=bar&foo=baz

回答by Malvolio

To escape a single value, Javascript has the function escape. You must provide your own function to iterate through the object, add the keys, and so on.

为了转义单个值,Javascript 具有函数escape. 您必须提供自己的函数来遍历对象、添加键等。

EDIT

编辑

Esailija is kind enough to remind me that escapedoes not handle many common cases properly, and encodeURIComponentis much better. If you're already using jQuery (and you should be), zzzzBov's answer is better still.

Esailija 好心地提醒我,escape很多常见的情况都没有妥善处理,而且encodeURIComponent要好得多。如果您已经在使用 jQuery(并且您应该使用),那么 zzzzBov 的答案仍然更好。