Thursday, May 16, 2013

Consuming a RESTful Service with jQuery.get()

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.


jQuery.get()

Loads data from the server using a HTTP GET request.



Examples:

Example: Request the test.php page, but ignore the return results.

1
$.get("test.php");

Example: Request the test.php page and send some additional data along (while still ignoring the return results).

1
$.get("test.php", { name: "John", time: "2pm" } );

Example: Pass arrays of data to the server (while still ignoring the return results).

1
$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );

Example: Alert the results from requesting test.php (HTML or XML, depending on what was returned).

1
2
3
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});

Example: Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).

1
2
3
4
$.get("test.cgi", { name: "John", time: "2pm" })
.done(function(data) {
alert("Data Loaded: " + data);
});

Example: Get the test.php page contents, which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>), and add it to the page.

1
2
3
4
5
$.get("test.php",
function(data) {
$('body').append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json");
 

Note : 

As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed theXMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases thejqXHR and textStatus parameters passed to the success callback are undefined.

No comments:

Post a Comment