Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery – AJAX get() and post() methods

jQuery - AJAX get() and post() methods


The jQuery get() and post() methods are used to request data from the server via HTTP GET or POST requests.


HTTP requests: GET vs POST

Two common methods for request-response between client and server are GET and POST.

GET is basically used to get (retrieve) data from the server. Note: The GET method may return cached data.

POST can also be used to get data from the server. However, the POST method does not cache data and is often used to send data along with the request.

To learn more about GET and POST and the differences between the two methods, read our HTTP methods - GET vs POST.


jQuery $.get() method

The $.get() method requests data from the server with an HTTP GET request.

Syntax:

$.get(URL,callback);

或

$.get( URL [, data ] [, callback ] [, dataType ] )

The following example uses the $.get() method to retrieve data from a file on the server:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$.

get

(

"

demo_test.php

"

,

function

(

data

,

status

)

{

alert

(

"

Data:

"

data

"

\n

Status:

"

status

)

;

}

)

;

}

)

;

Try it »

The first argument of $.get() is the URL we wish to request ("demo_test.php").

The second argument is the callback function. The first callback parameter holds the content of the requested page, and the second holds the status of the request.

Tip: This PHP file ("demo_test.php") looks something like this:

Code in the demo_test.php file:


jQuery $.post() method

The $.post() method submits data to the server with an HTTP POST request.

Syntax:

$.post(URL,callback);

或

$.post( URL [, data ] [, callback ] [, dataType ] )

The following example uses $.post() to send data along with the request:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$.

post

(

"

/try/ajax/demo_test_post.php

"

,

{

name

:

"

Runoob Tutorial

"

,

url

:

"

http://www.runoob.com

"

}

,

function

(

data

,

status

)

{

alert

(

"

Data:

\n

"

data

"

\n

Status:

"

status

)

;

}

)

;

}

)

;

Try it »

The first argument of $.post() is the URL we wish to request ("demo_test_post.php").

We then send the data along with the request (name and url).

The PHP script in "demo_test_post.php" reads these parameters, processes them, and returns the result.

The third argument is the callback function. The first callback parameter holds the content of the requested page, and the second holds the status of the request.

Tip: This PHP file ("demo_test_post.php") looks something like this:

Code in the demo_test_post.php file: