当前位置:首页 > PHP教程 > PHP高级教程

ajax 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 "输入成功";
?>

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!