Ajax提交post请求

来源:互联网 发布:c语言中变量的定义 编辑:程序博客网 时间:2024/05/21 07:12

前言:博主之前有篇文章是快速入门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 rel="stylesheet" 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" name="username" /><br/>        邮箱:<input type="text" name="email" /><br/>        <input type="submit" value="注册" />    </form>    <div id="regres"></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');
0 0
原创粉丝点击