欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AJAX PHP无刷新form表单提交的简单实现(推荐)

程序员文章站 2024-04-02 15:18:40
ajax.php:

ajax.php:

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>untitled document</title>
</head>

<script language="javascript">
function saveuserinfo()
{
//获取接受返回信息层
var msg = document.getelementbyidx_x("msg");

//获取表单对象和用户信息值
var f = document.user_info;
var username = f.user_name.value;
var userage = f.user_age.value;
var usersex = f.user_sex.value;

//接收表单的url地址
var url = "./ajax_output.php";

//需要post的值,把每个变量都通过&来联接
var poststr  = "user_name="+ username +"&user_age="+ userage +"&user_sex="+ usersex;

//实例化ajax
//var ajax = initajax();


      var ajax = false;
     //开始初始化xmlhttprequest对象
     if(window.xmlhttprequest) { //mozilla 浏览器
         ajax = new xmlhttprequest();
         if (ajax.overridemimetype) {//设置mime类别
             ajax.overridemimetype("text/xml");
         }
     }
     else if (window.activexobject) { // ie浏览器
         try {
             ajax = new activexobject("msxml2.xmlhttp");
         } catch (e) {
             try {
                 ajax = new activexobject("microsoft.xmlhttp");
             } catch (e) {}
         }
     }
     if (!ajax) { // 异常,创建对象实例失败
         window.alert("不能创建xmlhttprequest对象实例.");
         return false;
     }
        
        
        

//通过post方式打开连接
ajax.open("post", url, true);

//定义传输的文件http头信息
ajax.setrequestheader("content-type","application/x-www-form-urlencoded");

//发送post数据
ajax.send(poststr);

//获取执行状态
ajax.onreadystatechange = function() {
  //如果执行状态成功,那么就把返回信息写到指定的层里
  if (ajax.readystate == 4 && ajax.status == 200) {
   msg.innerhtml = ajax.responsetext;
  }
}
alert (username);
}
</script>
<body >
<div id="msg"></div>
<form name="user_info" method="post" action="">
姓名:<input type="text" id="user_name"name="user_name" /><br />
年龄:<input type="text" name="user_age" /><br />
性别:<input type="text" name="user_sex" /><br />

<input type="button" value="提交表单" onclick="saveuserinfo()">
</form>

</body>

 ajax_output.php:

<?php

   $username = $_post['user_name'];
   $userage = $_post['user_age'];
   $usersex = $_post['user_sex'];
  echo "$username <br>";
  echo "$userage <br>";
  echo "$usersex <br>";

  $db = new mysqli('localhost','root','123456','test');
  if(!$db){
  echo "连接失败!";
  }
  $db->query("set names utf8");
  $query = "insert into userinfo(uname,uage,usex) values ('".$username."','".$userage."','".$usersex."')";
  $result = $db->query($query);
  if ($result){
  echo "上传成功!";
  }
  else {
  echo "失败!";
  }
  $db->close();

?>

以上这篇ajax php无刷新form表单提交的简单实现(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。