How to send a string with & in it as a querystring value?
How can i send a string with a & in it (Ex : google & facebook) as the querystring value ? Now
var strUrl="ajaxpage.aspx?subject=my subject line &cmnt=google & facebook";
strUrl = encodeURI(strUrl);
$.ajax({ url: strUrl, success: function (data) {
alert(data)
}
});
Now when i read query stri开发者_开发问答ng "cmnt", I am getting only "google" because it breaks the &
What is the workaround for this ? Thanks
You will need to encode that character or the entire url
&
would be encoded as %26
var strUrl="ajaxpage.aspx?subject=my subject line &cmnt=google %26 facebook";
or call encodeURIComponent()
var strUrl = "ajaxpage.aspx"
+ "?subject=" + encodeURIComponent("my subject line")
+ "&cmnt=" + encodeURIComponent("google & facebook");
The short answer is: Use encodeURIComponent on data strings before sticking them in query strings.
The slightly longer answer is: You're using jQuery. It will fix this for you if you let it. Let the URL be just the URL to the main resource, then pass any data you want in the query string using the data
property of the object you pass to the ajax method.
$.ajax({
url: "ajaxpage.aspx",
data: {
subject: "my subject line",
cmnt: "google & facebook"
},
success: function (data) {
alert(data)
}
});
You can URL encode it as %26. Will that work for what you need to do?
Try using (see why) escape
encodeURIComponent
on 'google & facebook' and append to query string.
But I would recommend @Quentin's jQuery fix!
精彩评论