## HTTP 請求:GET vs. POST
兩種在客戶端和服務器端進行請求-響應的常用方法是:GET 和 POST。
* *GET*\- 從指定的資源請求數據
* *POST*\- 向指定的資源提交要處理的數據
GET 基本上用于從服務器獲得(取回)數據。注釋:GET 方法可能返回緩存數據。
POST 也可用于從服務器獲取數據。不過,POST 方法不會緩存數據,并且常用于連同請求一起發送數據。
如需學習更多有關 GET 和 POST 以及兩方法差異的知識,請閱讀我們的[HTTP 方法 - GET 對比 POST](https://www.w3cschool.cn/htmltags/html-httpmethods.html "HTTP 方法:GET 對比 POST")。
* * *
## jQuery $.get() 方法
[$.get() 方法](https://www.w3cschool.cn/jquery/ajax-get.html)通過 HTTP GET 請求從服務器上請求數據。
### 語法:
```
$.get(*URL*,*callback*);
```
必需的*URL*參數規定您希望請求的 URL。
可選的*callback*參數是請求成功后所執行的函數名。
下面的例子使用 $.get() 方法從服務器上的一個文件中取回數據:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool在線教程(w3cschool.cn)</title>
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("/statics/demosource/demo_test.php",function(data,status){
alert("數據: " + data + "\n狀態: " + status);
});
});
});
</script>
</head>
<body>
<button>發送一個 HTTP GET 請求并獲取返回結果</button>
</body>
</html>
```
$.get() 的第一個參數是我們希望請求的 URL("demo\_test.php")。
第二個參數是回調函數。第一個回調參數存有被請求頁面的內容,第二個回調參數存有請求的狀態。
**提示:**這個 PHP 文件 ("demo\_test.php") 類似這樣:
```
<?php
echo "This is some text from an external PHP file.";
?>
```
## jQuery $.post() 方法
[$.post() 方法](https://www.w3cschool.cn/jquery/ajax-post.html)通過 HTTP POST 請求從服務器上請求數據。
**語法:**
```
$.post(*URL,data,callback*);
```
必需的*URL*參數規定您希望請求的 URL。
可選的*data*參數規定連同請求發送的數據。
可選的*callback*參數是請求成功后所執行的函數名。
下面的例子使用 $.post() 連同請求一起發送數據:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("/statics/demosource/demo_test_post.php",
{
name:"W3Cschool",
url:"http://www.w3cschool.cn"
},
function(data,status){
alert("數據: " + data + "狀態: " + status);
});
});
});
</script>
</head>
<body>
<button>發送一個 HTTP POST 請求頁面并獲取返回內容</button>
</body>
</html>
```
$.post() 的第一個參數是我們希望請求的 URL ("demo\_test\_post.php")。
然后我們連同請求(name 和 city)一起發送數據。
"demo\_test\_post.php" 中的 PHP 腳本讀取這些參數,對它們進行處理,然后返回結果。
第三個參數是回調函數。第一個回調參數存有被請求頁面的內容,而第二個參數存有請求的狀態。
**提示:**這個 PHP 文件 ("demo\_test\_post.php") 類似這樣:
```
<?php
$name = isset($\_POST\['name'\]) ? htmlspecialchars($\_POST\['name'\]) : '';
$city = isset($\_POST\['city'\]) ? htmlspecialchars($\_POST\['city'\]) : '';
echo 'Dear ' . $name;
echo 'Hope you live well in ' . $city;
?>
```
**提示:**在jQuery中,[$.ajax()方法](https://www.w3cschool.cn/jquery/ajax-ajax.html)能夠實現與load()、$.get()和$.post()方法相同的功能,并且具有更多的作用!
- 簡介
- 安裝
- 語法
- 選擇器
- 事件
- click
- dblclick
- mouseenter
- mouseleave
- mousedown
- mouseup
- hover
- focus
- blur
- 鍵盤事件
- 效果
- 隱藏和顯示
- 淡入淡出
- 滑動
- 動畫
- 停止滑動
- jQuery Callback 方法
- jQuery Chaining
- jQuery_HTML
- jQuery獲取
- jQuery設置
- jQuery添加元素
- jQuery刪除元素
- jQuery CSS類
- jQuery css() 方法
- jQuery 遍歷
- jQuery AJAX
- jQuery AJAX簡介
- jQuery - AJAX load() 方法
- jQuery - AJAX get() 和 post() 方法