我对PHP很满意,但对jQuery完全不满意,并且在自动保存表单数据方面遇到了麻烦。
autosave
函数在dummy.php
中每30秒调用一次。我将要处理的序列化表单数据(-->数据库)发送到savetest.php
。
此刻,我陷入了一个问题:
如何让savetest.php
"监听"传入数据并对其做出反应
此时此刻,我收到了"哦,不!"(=没有成功)每30秒。
这是我缩短的样本代码:
dummy.php
,代码段1(HTML和PHP):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="../../_include/jquery-1.9.1.min.js"></script>
</head>
<body>
<h1>My Form</h1>
<form name="form1" id="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="radio" name="item_2_1" id="c_2_1_0" value="0" />
<input type="radio" name="item_2_1" id="c_2_1_1" value="1" />
<input type="radio" name="item_2_1" id="c_2_1_2" value="2" />
<input type="radio" name="item_2_1" id="c_2_1_3" value="3" />
<input type="checkbox" name="item_3_1[]" id="c_3_1_0" value="yes" />
<input type="checkbox" name="item_3_1[]" id="c_3_1_1" value="no" />
<input type="text" name="item_4_1" id="c_4_1_0" />
</form>
dummy.php
,代码段2(jQuery):
<script type="text/javascript">
function autosave() {
jQuery('form').each(function() {
jQuery.ajax({
url: 'savetest.php',
data: {
'autosave' : true,
'formData' : jQuery(this).serialize()},
type: 'POST',
success: function(data){
if(data && data == 'success') {
alert("OK!");
}else{
alert("Oh no!");
}
}// end successful POST function
}); // end jQuery ajax call
}); // end setting up the autosave on every form on the page
}// end function autosave()
jQuery(function($) {
setInterval(autosave, 30 * 1000);
});
</script>
这是savetest.php
:
if (isset($_POST)) {
var_dump($_POST);
exit();
} else {
echo 'Hi, no $_POST.';
}
不幸的是,仍然是不成功的警报。。。和CCD_ 8转储CCD_ 9:-(
if(isset($_POST)):
//processing to save autosave
else:
//the rest of your form code and jQuery stuff
endif;
这将检查数据是否已发布,//rest of your data
应表示不进行任何处理的页面生成的所有其他代码。
此外,我可以建议清理该数据属性吗?
data: {
'navigation': 'save',
'autosave' : true,
'formData' : jQuery(this).serialize()
}
然后在服务器端,您可以像正常情况一样访问它,$_POST['navigation']
和$_POST['formData']
包含name=value
组合的数组。
此外,您的函数应该在$(document).ready
中,或者类似于以下内容:
jQuery(function($){
//the rest of your code
});
jQuery(function($)
将作为$(document).ready
运行,并且在该函数内时将把$
符号别名为jQuery
。
这应该涵盖所有基地。