$.get() 與 $.post() 都接受三個參數:網址、資料、回呼函式。但網址本身也可以帶查詢字串(形如 get_data.php?v1=1&v2=2),而且第二個參數可以省略——直接寫回呼。那麼資料寫在網址後面,和寫在 data 參數裡,究竟有什麼不同?與其背結論,不如做實驗。
<?php echo "post: "; print_r($_POST); echo "get: "; print_r($_GET); ?>
$(function () {
$.post('jquery_data.php?v1=1', { v2: 2 }, function (data) {
$('<pre/>').append(data).appendTo('body');
});
});
結果:
post: Array ( [v2] => 2 ) get: Array ( [v1] => 1 )
兩邊各進各的容器,涇渭分明。
$(function () {
$.post('jquery_data.php?v1=1', function (data) {
$('<pre/>').append(data).appendTo('body');
});
});
結果,資料落在 get:
post: Array ( ) get: Array ( [v1] => 1 )
即使呼叫的是 $.post(),寫在網址上的參數依然以 GET 形式傳送。這一點很重要:方法名稱決定的是請求方法,不是參數位置。
$(function () {
$.get('jquery_data.php', { v2: 2 }, function (data) {
$('<pre/>').append(data).appendTo('body');
});
});
結果,資料落在 get:
post: Array ( ) get: Array ( [v2] => 2 )
$(function () {
$.get('jquery_data.php?v1=1', { v2: 2 }, function (data) {
$('<pre/>').append(data).appendTo('body');
});
});
結果,兩邊合併,全在 get:
post: Array ( ) get: Array ( [v1] => 1 [v2] => 2 )
$(function () {
$.get('jquery_data.php?v2=1', { v2: 2 }, function (data) {
$('<pre/>').append(data).appendTo('body');
});
});
結果,data 參數覆蓋了網址上的值:
post: Array ( ) get: Array ( [v2] => 2 )
五個實驗收斂出兩條規則:
$.get() 還是 $.post()。因此,為了避免混淆,建議統一把資料放在 data 參數裡,不要散落在網址上。唯一合理的例外,是你刻意要在 POST 請求中同時用 GET 帶一點識別資訊(例如快取破壞用的 _=timestamp)。
encodeURIComponent()。