这是如此基本,但我现在有时花了一些时间,但无法弄明白。
我正在尝试使用一个隐藏输入创建一个表单并将其提交给" test.php"使用jQuery的页面。但是,我无法访问此表单,因此我不确定问题出在哪里!!
这是用于创建和提交表单的jQuery:
$('#submitForm').on('click', function(e){
e.preventDefault();
//Create a Form
var f = document.createElement("form");
f.setAttribute('id','queryForm');
f.setAttribute('name','queryForm');
f.setAttribute('method',"post");
f.setAttribute('action',"test.php");
var i = document.createElement("input");
i.setAttribute("type", "hidden");
i.setAttribute('name',"query");
i.setAttribute('id',"queryId");
i.setAttribute("value", "success");
f.appendChild(i);
document.body.appendChild(f);
//Send the Form
f.submit();
});
在" test.php"我有下面的代码。我试图打印表格长度,以确保我正确提交表格,但我得到0 !!
<body>
<script>
var formlength = document.forms.length;
alert(formlength); // I get 0
</script>
</body>
提前致谢!
答案 0 :(得分:0)
document.forms.length
计算<form>
- 代码的数量而不是提交的数据。
至于你使用php(把它放在test.php中)。
<?php
if( isset($_POST['query']) ) {
echo htmlspecialchars( $_POST['query'] );
}
看看这里:http://jsfiddle.net/428GQ/1/。我已经注释掉了提交并将隐藏字段更改为文本(只是为了确保它有效)。现在将上面的代码添加到test.php并观察它是否正常工作(当然你必须先删除注释)。
答案 1 :(得分:0)
jQuery代码很好。将此行放在test.php文件中以测试它:
<?php echo $_POST['query']; ?>
它应该在test.php页面上输出“success”
答案 2 :(得分:0)
我改变你的代码以使用更多的Jquery,并且[Niclas Larsson]的建议把它放在页脚中..请检查这个
$(窗口).load(()的函数 {
//Create a Form
var f = document.createElement("form");
$(f).attr('id','queryForm');
$(f).attr('name','queryForm');
$(f).attr('method',"post");
$(f).attr('action',"test.php");
var i = document.createElement("input");
$(i).attr("type", "hidden");
$(i).attr('name',"query");
$(i).attr('id',"queryId");
$(i).attr("value", "success");
$(f).append(i);
$('body').append(f);
console.log(f);
//Send the Form
$(f).submit();
});