jQuery $.post - do I have to encode the URL parameter?
I'm making an AJAX call with $.post(url, cb)
. The URL I'm passing in could potentially have weird characters like spaces, &
, ?
and so on.
Do I have to use $.post(encodeURIComponent(url), cb)
?
url
is something like /foo/weird-char§
.开发者_如何学Go
Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent()
but not on the entire URI, only on the data part (weird
and chars
in your example). The URL and the ? &
separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data
parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.
Yes, you would need to encode the keys and values in the query string (but not the ?
which separates the path from the query arguments and the &
which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post
, like so:
$.post(url, { name: "John", time: "2pm" }, cb);
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
精彩评论