[英]Using jQuery .serialize() within ajax array to pass the PHP $_POST as Variables?
这是我用来将表单详细信息发送到php函数的jQuery代码:
jQuery(document).ready(function($) {
jQuery('.submit').click(function(){
var str = $("#ajaxForms").serialize();
var data = {
action: 'myajax-submit',
serialize: str,
beforeSend: function(){
alert('Sending...');
}
};
jQuery.post(MyAjax.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
return false;
});
});
这是php函数:
function myajax_submit() {
$whatever = $_POST['serialize'];
echo $whatever;
die();
}
一切正常,但是当出现警告框时,文本会显示我的html表单#ajaxForms
。 我相信这是因为php函数回显了$_POST['serialize']
。
在我的表格中,我有一个输入框,如:
<input id="postID" name="postID" value="First Name" type="text" />
但是当我尝试回显php中的$_POST['postID']
变量时,它不会在警告框中显示任何内容。
我想通过将表格数据序列化发送到php函数,我可以使用与表单输入相关联的$ _POST变量吗?
帮助赞赏。 :)
通过使用jQuery的序列化序列化表单输入,您可以创建一个字符串,如:
a=1&b=2&c=3&d=4&e=5&postID=10
为了获得postId,你需要反序列化$ _POST ['serialize']。 为此,您应该执行以下操作:
parse_str($_POST['serialize'], $whatever);
现在, $whatever['postID']
你在寻找$whatever['postID']
。
编辑:修复parse_str():)
你以错误的方式实现$.post
。 .serialize()
返回一个字符串。 因此,当您将serialize: str
传递给$.post()
,表单本身不再被添加,而是包含序列化表单的纯字符串。
下面的代码是正确的,使用$.ajax
(参见注释行)。
jQuery('.submit').click(function(){
var str = $("#ajaxForms").serialize();
// If you realllly. want a parameter serialize, uncomment the following line
// str += '&serialize=' + encodeURIComponent(str);
str += '&action=myajax-submit';
jQuery.ajax(MyAjax.ajaxurl, {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.