Sho*_*box 8 php jquery serialization
这是我用来将表单详细信息发送到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;
});
});
Run Code Online (Sandbox Code Playgroud)
这是php函数:
function myajax_submit() {
$whatever = $_POST['serialize'];
echo $whatever;
die();
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但当出现警告框时,文本会显示我的html表单中的一串值#ajaxForms.我相信这是因为php函数回声了$_POST['serialize'].
在我的表格中,我有一个输入框,如:
<input id="postID" name="postID" value="First Name" type="text" />
但是当我尝试回显$_POST['postID']php中的变量时,它不会在警告框中显示任何内容.
我想通过将表格数据序列化发送到php函数我可以使用与表单输入相关联的$ _POST变量吗?
帮助赞赏.:)
mob*_*ius 10
通过使用jQuery的序列化序列化表单输入,您可以创建一个字符串,如:
a=1&b=2&c=3&d=4&e=5&postID=10
Run Code Online (Sandbox Code Playgroud)
为了获得postId,你需要反序列化$ _POST ['serialize'].为此,您应该执行以下操作:
parse_str($_POST['serialize'], $whatever);
Run Code Online (Sandbox Code Playgroud)
现在$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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14517 次 |
| 最近记录: |