How to Use the jQuery get() Method
jQuery's get()
method is a convenience function that can be used for making a simple GET
request. The following six steps show how to get started.
- Download the jQuery library from jquery.com or find a link to the latest version of jQuery by going to code.jquery.com.
- Create an HTML document that includes the jQuery library.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> </body> </html>
- Inside a
script
element in your HTML document, write jQuery'sready()
function, which will wait until the selected object (the HTML document in this case) is ready before executing the code passed into it.<script> $(document).ready(function() { }); </script>
- Write the
get()
method inside the body of the function passed into theready()
method. The only required argument is the first one, which is the URL to make the request to.<script> $(document).ready(function() { $.get('users'); }); </script>
- After the URL, pass any of the following arguments to
get()
:- data - The data to be sent to the server. This can either be an object, like
{foo:'bar',baz:'bim' }
, or a query string, such asfoo=bar&baz=bim
. - success - A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
- dataType - The type of data you expect back from the server.
- data - The data to be sent to the server. This can either be an object, like
- Write a success callback function, which will receive the result of the request.
$.get('users','userID=8', function(user) { $('<h1/>').text('Welcome ' + user.firstName).appendTo('body'); },'json');