说明:
页面中有一个form,一个button按钮,尝试以ajax方式无刷新提交表单。
页面代码为:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>xhr对象</title> </head> <body> <!--用之前的登陆表单讲解--> <h3>用户登陆</h3> <form action="check.php" method="post"> <p>用户名: <input type="text" name="userName" placeholder="不少于8位"></p> <p>密 码: <input type="password" name="password" placeholder="不少于6位"></p> <button type="button">提交</button> </form> </body> </html>
ajax代码为:
<script>
//要点:将表单的提交行为交给一个js脚本来处理,这时该脚本充当了客户端的角色,因为这个脚本也可以送一个请求
//获取提交按钮
var submit = document.getElementsByTagName('button')[0]
//给该提交按钮添加点击事件
submit.onclick = function () {
//1.创建ajax对象
var xhr = new XMLHttpRequest()
//2.用onreadystatechange事件检测客户端准备状态
xhr.onreadystatechange = function () {
//如果客户端请求状态等于4,并且服务器端http响应状态为200,则表示请求成功
if (xhr.readyState == 4 && xhr.status == 200) {
//执行DOM操作
alert('返回')
}
}
//3. 调用 open()方法来初始化一个客户端的ajax请求
xhr.open('post', 'check.php', true)
//4. 设置头信息,将内容类型设置为表单提交方式
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
//5. 以表单数据为参数,将请求发送到服务器端处理
var data = serialize(document.forms[0])
// var data = "userName=admin&password=111";
xhr.send(data)
}
</script>PHP文件代码为:
<?php //测试是否获取到了数据 print_r($_POST);
测试一:button类型为button
<button type="button">提交</button>
代码报错:serialize is not defined(serialize 不是js原生函数,执行到此处报错)

serialize 的问题另说,报错说明,ajax部分的代码是被执行了。
另外,日志中没有XMLHttpRequest,说明ajax并没有成功提交。
整个页面也没有刷新。
测试二:button类型改为submit(不写类型默认为submit)
<button>提交</button>
页面跳到了check.php文件,显示出了表单内容:

分析:仍然报错,另外也没有XMLHttpRequest日志,说明ajax并没有成功提交
但是,跳转到了php页面,也显示出了表单数据。
既然ajax没有成功提交表单,那就是由button提交了表单。
小结:
页面中有form时,如果要用button 的onclick事件,Ajax无刷新提交表单,应当设置button的类型为"button",
即:
<button type="button">提交</button>
或者,使用其它元素绑定合适的事件来提交。
serialize 序列化表单的问题是另外的情况,这里不做讨论。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号