Ajax提交post请求案例阐明

媒介:博主之前有篇文章是快速入门Ajax ,主要是操作Ajax做简朴的get请求,本日给各人分享一篇操作Ajax提交post请求,以及利用post时需要留意的处所,照旧以案例的方法汇报各人。

案例:

注册表单

文件布局图:

06-ajax-reg.html文件:

页面中主要有一个表单,利用了onsubmit事件,在onsubmit事件中首先获取筹备post的内容,然后建设XMLHttpRequest工具,接着确定请求参数,然后重写回调函数,在函数中主要是按照请求的状态来利用处事器端返回值,然后发送请求,最后返回false,让表单无法提交,从而页面也不会跳转。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>无刷新用户注册界面</title> <link href=""> </head> <script> //建设XMLHttpRequest工具 function createXhr(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest();//谷歌、火狐等欣赏器 }else if(window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP");//ie低版本 } return xhr; } //注册要领 function reg(){ //1、获取筹备Post内容 var username = document.getElementsByName('username')[0].value; var email = document.getElementsByName('email')[0].value; //2、建设XMLHttpRequest工具 var xhr = createXhr(); //3、确定请求参数 xhr.open('POST','./06-ajax-reg.php',true); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //4、重写回调函数 xhr.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ //利用处事器端返回值 var regres = document.getElementById('regres'); regres.innerHTML = this.responseText; } } //5、发送请求 var content = 'username='+username+'&email='+email; xhr.send(content); return false;//不跳转页面 } </script> <body> <h1>无刷新用户注册界面</h1> <form onsubmit="return reg();"> 用户名:<input type="text" /><br/> 邮箱:<input type="text" /><br/> <input type="submit" value="注册" /> </form> <div></div> </body> </html>

06-ajax-reg.php文件:

代码较量简朴,主要是判定内容是否为空,为空则返回“内容填写不完整”,不为空则打印提交的内容,返回“注册乐成”。

<?php /** * ajax注册措施 * @author webbc */ header('Content-type:text/html;charset=utf-8'); if(trim($_POST['username']) == '' || trim($_POST['email']) == ''){ echo '内容填写不完整'; }else{ print_r($_POST); echo '注册乐成'; } ?>

结果图:

这里写图片描写

留意事项:

博主以前利用过Jquery的Ajax,利用$.post函数时不需要指定请求头的Content-Type内容为application/x-www-form-urlencoded,是因为jquery内里内置了,可是利用原生的Ajax,也就是XMLHttpRequest函数时必需加上。

XMLHttpRequest发送post请求时必需配置以下请求头:

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

更多关于ajax相关内容感乐趣的读者可查察本站专题:《jquery中Ajax用法总结》、《JavaScript中ajax操纵能力总结》、《PHP+ajax能力与应用小结》及《asp.net ajax能力总结专题

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsdfyf.html