Reputation: 1655
I'm making an ajax request and I have some problems, this is my jquery code:
var url = "http://www.domain.com/SearchService.svc/search?keyword=my search keywords";
$.ajax({
type: "GET",
url: url,
dataType: "json".......
.....
When making this request I sometimes have blank spaces in my search (var url) and then the keywords get cutted so in the example above for example it just searches for "my". I understand this is a quite simple question and that must be an easy solution. Just couldn't find a solution...
Thanks for your help!
Upvotes: 10
Views: 20236
Reputation: 816542
You can use encodeURI
:
var url = encodeURI("http://www.domain.com/SearchService.svc/search=my search keywords");
This encodes the URL and converts the blanks and any other 'unsafe' character for URL usage.
See also encodeURIComponent
for safely encoding data to be inserted into a URI.
Upvotes: 16
Reputation: 12711
You could do
var url = "http://www.domain.com/SearchService.svc/search?keyword="
+ encodeURIComponent("my search keywords");
While escape() might as well work for you, there are situations that only encodeURIComponent() will work, such as for characters & = + etc.
Upvotes: 2
Reputation: 54074
Just convert whitespaces in url format. For each whitespace char use %20 instead:
var url = "http://www.domain.com/SearchService.svc/search=my%20search%20keywords";
$.ajax({
type: "GET",
url: url,
dataType: "json".......
.....
Or if you want to make it in a more automatic way just use the javascript function escape()
like Felix suggested.
Upvotes: 1
Reputation: 449515
You can escape the search keyword in the URL but the right thing to do is to add search
as a parameter to the ajax request.
var url = "http://www.domain.com/SearchService.svc/search=my search keywords";
$.ajax({
type: "GET",
url: url,
data: { "search" : "my search keywords" }
dataType: "json".......
Upvotes: 2