纯javascript的ajax实现php异步提交表单的简单实例

等你,十一月的冷风款款如约而至,尽是点滴的韵致,点点滴滴都是我的凝眸。想你,十一月的叶落纷纷布满角落,全是颗粒的珠链,颗颗粒粒都是我的心忆。爱你,十一月的阳光惨惨敷在脸庞,满是残熠的余辉,残残熠熠都是我的思绪。

很多时候需要异步提交表单,当表单太多是时候,一个个getElementById变得很不实际

当然,jquery可以实现异步提交表单,jquery.form.js这个库貌似也挺流行

只是有时候并不想使用额外的库,所以就琢磨着自己写,用纯js来实现异步提交表单

实现如下(本例用POST方式提交,用php作为服务器脚本)

HTM L文件:test

<html>
<head>
  <script type="text/javascript" src="name_form.js"></script>
</head>
<body>
  <form action="process.php" id="ajax_form">
    Username:<input type="text" name="username" id="username"/><br>
    <input type="button" onclick="submitForm('name_form')" value="Submit">
  </form>
  <div id="tip"></div>
</body>
</html>

JS文件:name_form.js

function createXmlHttp() {
  var xmlHttp = null;
   
  try {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    //IE
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
   
  return xmlHttp;
}
 
function submitForm(formId) {
  var xmlHttp = createXmlHttp();
  if(!xmlHttp) {
    alert("您的浏览器不支持AJAX!");
    return 0;
  }
  
  var url = 'test.php';
  var postData = "";
  postData = "username=" + document.getElementById('username').value;
  postData += "t=" + Math.random();
  
  xmlHttp.open("POST", url, true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      if(xmlHttp.responseText == '1') {
        alert('post successed');
      }
    }
  }
  xmlHttp.send(postData);
}

PHP文件:test.php

<?php
  if(isset($_POST['username']) {
    echo '1';
  }
?>

上面程序的原理是,首先用户用过在test.html文件中输入用户名信息,然后通过name_form.js文件进行ajax实现提交表单,然后在php文件中进行操作,此处只是判断用户名是否被设定,也就是说用户名是否存在,存在则输出1;另外,也可以对数据库进行操作(增,改等),然后判断操作结果,如果结果为真则输出1,在js文件中的xmlHttp.responseText中判断返回的信息,因为只是输出1,所以判断正确,此时弹出提示框,内容是'post successed'。这样就成功实现了用ajax实现php异步提交表单。

注:要保证php文件echo之前没有任何的输出,这样ajax才能准确地获取返回的信息。

以上这篇纯javascript的ajax实现php异步提交表单的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签: javascript ajax