Reputation: 218722
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 string "cmnt", I am getting only "google" because it breaks the &
What is the workaround for this ? Thanks
Upvotes: 1
Views: 313
Reputation: 63512
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");
Upvotes: 5
Reputation: 76208
Try using (see why) escape
encodeURIComponent
on 'google & facebook' and append to query string.
But I would recommend @Quentin's jQuery fix!
Upvotes: 0
Reputation: 952
You can URL encode it as %26. Will that work for what you need to do?
Upvotes: 0
Reputation: 943220
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)
}
});
Upvotes: 3