Java Reference
In-Depth Information
With the $.get() method, you can do the same thing by passing an object containing the key/value
pairs to the method. For example:
var parms = {
username = "jmcpeak"
};
function handleResponse(json) {
var obj = JSON.parse(json);
// do something with obj
}
$.get("phpformvalidator.php", parms, handleResponse);
This code creates a new object called parms , and it has a username property with the value
of jmcpeak . This object is passed to the $.get() method as the second argument, with the
handleResponse() callback function passed as the third.
You can send as many parameters as you need; simply add them as properties to the parameter
object.
automatically parsing JSON Data
In Chapter 14, the form validator PHP file returns the requested data in JSON format, and notice
that the previous sample code expects JSON data and parses it with the JSON.parse() method.
jQuery can eliminate this step and parse the response for you. Simply use the $.getJSON() method
instead of $.get() . For example:
var parms = {
username = "jmcpeak"
};
function handleResponse(obj) {
// obj is already an object
}
$.getJSON("phpformvalidator.php", parms, handleResponse);
This code is almost identical to the previous example except for two things. First, this code uses
$.getJSON() to issue a request to the PHP file. By doing so, you are expecting JSONā€formatted data
in the response, and jQuery will automatically parse it into a JavaScript object.
The second difference is inside the handleResponse() function. Because the response is
automatically parsed, you don't have to call JSON.parse() in handleResponse() .
the jqXhr Object
As you've seen in the previous sections, jQuery's get() and getJSON() methods do not actually
return the data you requested; they rely upon a callback function that you provide and pass the
requested data to it. But these methods do, in fact, return something useful: a special jqXHR object.
 
Search WWH ::




Custom Search