I’d like to make an ajax call as a POST, it’s going to go to my servlet. I want to send parameterized data, like the following:
var mydata = 'param0=some_text¶m1=some_more_text';
I supply this as the ‘data’ parameter of my jquery ajax() call. So this should be inserted in the body of the POST, right? (I mean, not appended to my ‘mysite/save’ url?):
$.ajax({
url: 'mysite/save',
type: 'POST',
data: mydata
});
it appears to work correctly. In my servlet, I am just dumping all received parameters, and I see them all come through nicely:
private void printParams(HttpServletRequest req) {
Enumeration paramNames = req.getParameterNames();
while (paramNames.hasMoreElements()) {
// print each param key/val here.
}
}
also, I should url encode my data string manually before use, right? Like:
var mydata = 'param0=' + urlencode('hi there!');
mydata += '¶m1=' + urlencode('blah blah');
mydata += '%param2=' + urlencode('we get it');
Thanks!
An easier way is to provide the
dataproperty as an object, like this:Otherwise, yes you should encode it, as anything with an
&for example would screw things up very quickly. Providing it as an object represents a much clearer/simpler approach though, in my opinion anyway.You can also space it out and retrieve properties from other places inline, like this:
Edit: If you’re curious how jQuery does this encoding internally, it’s using
$.param()(which you can use directly as well) to encode the object to a string, called here, and the guts here.