2011-07-21 193 views
8

我想將數據發送到我的PHP腳本來處理一些東西並生成一些項目。Ajax將數據傳遞給php腳本

$.ajax({ 
    type: "POST", 
    url: "test.php", 
    data: "album="+ this.title, 
    success: function(response) { 
     content.html(response); 
    } 
}); 

在我的PHP文件中,我嘗試檢索專輯名稱。雖然當我確認了,我創建了一個警報顯示什麼albumname是我得到什麼,我試圖通過$albumname = $_GET['album'];

拿到專輯名稱雖然會說不確定的:/

回答

30

您發送POST AJAX請在您的服務器上使用$albumname = $_POST['album'];來獲取該值。此外,我建議你寫這樣的要求,以確保正確的編碼:

$.ajax({ 
    type: 'POST', 
    url: 'test.php', 
    data: { album: this.title }, 
    success: function(response) { 
     content.html(response); 
    } 
}); 

或在較短的形式:

$.post('test.php', { album: this.title }, function() { 
    content.html(response); 
}); 

,如果你想使用一個GET請求:

$.ajax({ 
    type: 'GET', 
    url: 'test.php', 
    data: { album: this.title }, 
    success: function(response) { 
     content.html(response); 
    } 
}); 

或其較短的形式:

$.get('test.php', { album: this.title }, function() { 
    content.html(response); 
}); 

現在在您的服務器上,您將能夠使用$albumname = $_GET['album'];。儘管使用AJAX GET請求時要小心,因爲它們可能會被某些瀏覽器緩存。爲避免緩存它們,您可以設置cache: false設置。

+0

感謝這對我工作使用GET。無法解決這個問題:/非常感謝! – NeedHelp

+0

$ .get('test.php',{album:this.title}我想問如何發送兩個值 –

+1

@ M.chaudhry您可能已經發現了這一點,但對於未來的讀者,這是[JSON]( http://en.wikipedia.org/wiki/JSON),所以要發送多個值,你只需添加一個逗號,如下所示:'$ .get('test.php',{album:this.title,歌曲:that.title});' – Ian

9

嘗試發送的數據是這樣的:

var data = {}; 
data.album = this.title; 

然後你就可以訪問它像

$_POST['album'] 

注意不是「GET」

2

您還可以使用波紋管碼通數據使用ajax。

var dataString = "album" + title; 
$.ajax({ 
    type: 'POST', 
    url: 'test.php', 
    data: dataString, 
    success: function(response) { 
     content.html(response); 
    } 
});