views:

189

answers:

4

I am using the post and get methods for Ajax calls, and have a general question. There are two methods I've seen people use on the web:

  1. Construct the URL and parameters by hand
  2. Use the data parameter

Both approaches work. I've included them below:

// Construct the POST URL by hand
queryStringDelimiter = "?";
settings.queryParam = "q";
$.post(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType);

// Use the data param
$.post(settings.url, {q:query}, callback, settings.contentType);

Are there any situations where you would construct the URL and parameters by hand instead of using the built-in data parameter? Any advantages of one method over the other?

A: 

If I am using a GET I tend to just construct the URL, but when using POST I use the data parameter.

I do it because it is closer to how I was doing ajax calls before jQuery, when I wrote everything myself.

James Black
+1  A: 

No reason I can think of why one would construct them by hand unless they didn't know of the data parameter if there's more than 1 or 2 parameters, it's also cleaner to keep them separated so if you have to loop through the data object and possibly modify some values you'd just iterate over the object instead of parsing a string manually.

meder
+4  A: 

I'd say the data approach is better since it formalizes the process and reduces the chances of producing errors while string building. Besides, the JQuery library will do the string building for you so its basically the same amount of work.

Soviut
+1  A: 

If you let jQuery concatenating the data in to the appropriately formatted string you...

  1. avoid having to duplicate that code...
  2. avoid worrying about escaping the data for transport...
  3. can easily switch between GET and POST requests in the future...

Really, the only argument AGAINST using the data parameter is if you already have the data in a concatenated format.

coreyward