[英]Pass data from jQuery to PHP for an ajax post
你好我是一个使用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 '<script>console.log("post contacts");</script>';
}
但我对如何检索数据感到困惑。 任何帮助表示赞赏。 我正在使用cakePHP,所以我不得不使用autoRender = false; 这使视图可选。
使用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"
数据参数应该是具有键和值的对象。
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
<?
echo 'Your ajax post data was '. $_POST['MyFieldName'];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.