2010-11-17 92 views
7

您好,我是一名使用jQuery和Ajax的新手。我正在嘗試使用Jquery POST方法將數據提交給服務器。我傳遞的數據是一個字符串。現在我無法理解如何傳遞數據以及如何檢索數據。我試過爲我的問題搜索文章,但我沒有找到。我相信我的問題是非常基本的。將數據從jQuery傳遞到PHP以獲得ajax帖子

if (1)//validateStep(step) 
{ 
if(step==1) 
{ 
var data = document.getElementById('hiddenContact').value; 
$.post('/callcenter/admin/postContacts', data); 
} 
} 

現在我將發佈我的postContacts操作的代碼,這不是一件大事。

function postContacts() 
{ 
$this->autoRender = false; 
echo '<script>console.log("post contacts");</script>'; 
} 

但我很困惑,如何將數據必須被檢索。任何幫助表示讚賞。我正在使用cakePHP,所以我必須使用autoRender = false;這使得視圖是可選的。

回答

16

隨着jQuery post可以定義時,返回的數據時執行的回調函數:

$.post('/callcenter/admin/postContacts', data, function(returnedData) { 
    // do something here with the returnedData 
    console.log(returnedData); 
}); 

data應該是形式:

{name: 'value', anotherName: 'another value'} 

這相當於該職位的名稱上PHP可以像普通PHP那樣訪問:

echo $_POST['name'];   # prints "value" 
echo $_POST['anotherName']; # print "another value" 
2

數據參數應該是具有鍵和值的對象。

var data = { 
    hiddenContact: document.getElementById('hiddenContact').value 
} 
$.post('/callcenter/admin/postContacts', data); 

然後在PHP中,你可以這樣獲取:

$hiddenContact = $_POST["hiddenContact"]; 

我不是一個大CakePHP的用戶,但我相信CakePHP的版本是這樣的:

$hiddenContact = $this->params["hiddenContact"]; 
1
//javascript 
if(step==1) 
{ 
    var data = {'MyFieldName':document.getElementById('hiddenContact').value}; 
    $.post('/callcenter/admin/postContacts', data, function(returnData){ 
     alert('The server said ' + returnData); 
    }); 
} 

//read the post in php 
<? 
    echo 'Your ajax post data was '. $_POST['MyFieldName']; 
?>