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表單提交的簡單實現(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持幫客之家。