程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> ajax php 實現寫入數據庫

ajax php 實現寫入數據庫

編輯:PHP綜合
首先需要一個帶輸入表格.
復制代碼 代碼如下:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="submit.js" language="javascript"></script>
</head>
<body>
Insert 知識點
<form name="insertForm">
<label for="question"></label>知識點
<input name="question" type="text"/>
<br/><br/>
<label for="answer"> 答案</label>
<input name="answer" type="text"/>
<br/>
<br/>
<input name="confirm" value="添加" type="button" onclick="getValue();">
</form>
</body>
</html>

需要js來處理提交數據到服務器上以及從服務器獲取提交後的返回數據. submit.js代碼如:
復制代碼 代碼如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
var xmlHttp;
function getValue(){
alert("getvaluel");
var question =document.insertForm.question.value;
// alert(question);
var answer = document.insertForm.answer.value;
// alert(answer);
submit(question,answer);
};
function submit(question,answer){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
xmlHttp.onreadystatechange =function(){
if(xmlHttp.readyState ==4){
alert(xmlHttp.responseText);
}
};
var url = "insert1.php";
xmlHttp.open("post",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
xmlHttp.send("question="+question+"&answer="+answer);

}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

然後PHP處理界面,負責跟服務器交換數據
復制代碼 代碼如下:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//echo $_POST["question"];
//echo $_POST["answer"];
$q =$_POST['question'];
$a = $_POST['answer'];
//$q='qq';
//$a="a";
$con = mysql_connect("localhost","joe","123");
if (!$con)
{
//die('Could not connect: ' . mysql_error());
echo 'Could not connect: ' . mysql_error();
}
mysql_select_db("joe",$con);
mysql_query("INSERT INTO message VALUES ('$q', '$a', '無')");
mysql_close($con);
echo "輸入成功";
?>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved