清空$_GET和$_POST,表单使用form.submit()


Empty $_GET and $_POST with form using form.submit()

我想在提交之前测试连接。与该解决方案不同,我使用的是非Jquery解决方案(因为我不想使用那种语言,而且我认为没有必要加载库)。

该代码在测试连接和发送或不发送表单时工作良好。

问题似乎是在xhr.onreadystatechange中使用formTemp.submit(),发送没有输入的表单。

我是这样做的:

//Test connection on form
var myForm = document.getElementsByTagName('form');
for (var i = 0 ; i <myForm.length; i++){
	(function(){
		var currentI = i;
		addEvent(myForm[currentI],'submit', function(e) {
			e = e || window.event; //In case IE
			e.preventDefault(); //Prevent the Form to be sent
			TestConnection_js(this);
		});
	})();
}
function addEvent(element, event, func){ 
	if (element.addEventListener){
		element.addEventListener(event, func, false);
	} else { //In case IE
		element.attachEvent('on'+event, func);
	}
}
var TestConnection_js = function (formTemp){
	var xhr = new XMLHttpRequest();
	xhr.open('GET', './index.php');
	xhr.onreadystatechange = function(){
		console.log(xhr.readyState+' - '+xhr.status);
		if (xhr.readyState == 4 && xhr.status == 200) {
			formTemp.submit(); //Here is my Submit (that submit nothing)
		} else {
			alert('Connection Error');
		}
	};
	xhr.send(null);
	return xhr;
}
<!-- What's on page : here.php -->
<form action="aim.php" method="post">
  <input type="submit"  value="Aim" />
</form>
<!-- What's on page : aim.php -->
<?php print_r ($_GET);
      print_r ($_POST); ?>

我想它最终出现在aim.php上意味着成功测试,所以你能告诉我这里出了什么问题吗?

编辑:忘记了表格上的method="post",但这不是问题所在。

问题:
1.TestConnection_js函数发出GET请求,因此print_r($_POST);中没有任何数据
2.ajax请求是向index.php而不是aim.phpxhr.open('GET', './index.php');)发出的
3.ajax请求未发送任何数据,因此即使是print_r($_GET);也将没有数据
4.如果您想发送POST请求,我认为这就是您想要的,您必须序列化表单并向aim.php文件发出POST ajax请求

解决方案:
1.我建议您使用javascript框架(如jQuery),它可以执行您想要的大部分代码,并且代码与跨浏览器兼容。看看jQuery ajax POST请求
另外,看看这个带有表单数据的jQueryPOST请求示例
2.使用浏览器中集成的开发工具。我最喜欢的工具是Firefox的Firebug。通过这种方式,您可以准确地看到浏览器发出的每个请求以及发送/接收的数据。