将数据从jQuery传递到PHP以获取ajaxpost

你好,我是一个使用jQuery和Ajax的新手。 我正在尝试使用Jquery POST方法将数据提交到服务器。 我传递的数据是一个字符串。 现在我无法理解如何传递数据以及如何检索数据。 我试过为我的问题搜索文章,但我没找到。 我相信我的问题非常基础。

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 'console.log("post contacts");'; } 

但我对如何检索数据感到困惑。 任何帮助表示赞赏。 我正在使用cakePHP,所以我不得不使用autoRender = false; 这使视图可选。

使用jQuery post,您可以定义一个回调函数,该函数在返回数据时执行:

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

data应采用以下forms:

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

这相当于PHP端的post名称可以在普通的PHP中访问,如下所示:

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

数据参数应该是具有键和值的对象。

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

然后在PHP中,您可以像这样检索它:

 $hiddenContact = $_POST["hiddenContact"]; 

我不是一个很大的CakePHP用户,但我相信CakePHP版本是这样的:

 $hiddenContact = $this->params["hiddenContact"]; 
 //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