当前位置: 移动技术网 > IT编程>脚本编程>Ajax > Ajax提交post请求案例分析

Ajax提交post请求案例分析

2019年09月09日  | 移动技术网IT编程  | 我要评论

王珉是王冶平的侄子,悟道真源,郭德纲 九尾狐

本文实例讲述了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 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');

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网