jQuery - AJAX get()/post() methods
jQuery - AJAX get() and post() methods
jQuery get() and post() methods are used for HTTP GET or POST requests request data from the server.
HTTP request: GET vs. POST
Both requests are made on the client side and the server side -Common methods of response are: GET and POST.
GET - Request data from the specified resource
POST - Submit the data to be processed to the specified resource
GET is basically used to obtain (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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $.get("/try/ajax/demo_test.php",function(data,status){ alert("数据: " + data + "\n状态: " + status); }); }); }); </script> </head> <body> <button>发送一个 HTTP GET 请求并获取返回结果</button> </body> </html>
Run instance»Click the "Run instance" button to view the online instance
?>
jQuery $.post() method
$.post() Method requests data from the server via HTTP POST request. Syntax:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $.post("/try/ajax/demo_test_post.php",{ name:"菜鸟教程", url:"http://www.runoob.com" }, function(data,status){ alert("数据: \n" + data + "\n状态: " + status); }); }); }); </script> </head> <body> <button>发送一个 HTTP POST 请求页面并获取返回内容</button> </body> </html>
Run Example » Click the "Run Instance" button to view the online instanceThe first parameter to
$.post() is the URL we wish to request ("demo_test_post.php").
Then we send the data along with the request (name and city).
The PHP script in "demo_test_post.php" reads these parameters, processes them, and returns the results.
The third parameter is the callback function. The first callback parameter stores the content of the requested page, while the second parameter stores the status of the request.
Tips: This PHP file ("demo_test_post.php") is similar to this:
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$city = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo 'Website name: ' . $name;
echo "\n";
echo 'URL address: ' .$city;
?>
##