编码要发送到Web服务器的查询字符串时 - 何时使用escape()以及何时使用encodeURI()或encodeURIComponent():
使用转义:
escape("% +&=");
Run Code Online (Sandbox Code Playgroud)
要么
使用encodeURI()/ encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
Run Code Online (Sandbox Code Playgroud) 从旧帖子:我应该使用encodeURI或encodeURIComponent来编码URL吗?, 它说:
encodeURI assumes that the input is a complete URI that might have some
characters which need encoding in it.
encodeURIComponent will encode everything with special meaning, so
you use it for components of URIs such as
Run Code Online (Sandbox Code Playgroud)
如果我需要编码URIas查询字符串参数怎么办?
例如
var url = "http://example.com/?next=" + encodeURI(url)
or
var url = "http://example.com/?next=" + encodeURIComponent(url)
Run Code Online (Sandbox Code Playgroud) 在一个小的asp.net webclient中,我有以下Ajax调用.
$.ajax({
type: "GET",
url: "Search.aspx?action=GetDocumentInfoByChronicleId&" + querystring
})
.success(function (msg) {
$("#documentcontent").html(msg);
})
Run Code Online (Sandbox Code Playgroud)
querystring默认字符的工作原理但在使用特殊字符时似乎不起作用(参见下面的示例)
objectId=09028139800c59e3&Db=DIV_Firm <== Works
objectId=090281>>773c5983&Db=DIV_Firm <== Non Working
Run Code Online (Sandbox Code Playgroud)
基于此(以及更多关于SO的帖子我选择改变我的ajax调用如下(EncodeUriComponent).但似乎没有一个工作(即使使用原始的查询字符串).
有人能向我指出我做错了什么吗?
$.ajax({
type: "GET",
url: "Search.aspx?action=GetDocumentInfoByChronicleId&" + encodeURIComponent(querystring)
})
.success(function (msg) {
$("#documentcontent").html(msg);
})
Run Code Online (Sandbox Code Playgroud)
注意: EncodeUri似乎工作正常.但我更喜欢使用EncodeUriComponent