ajax php 实现写入数据库

前端之家收集整理的这篇文章主要介绍了ajax php 实现写入数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首先需要一个带输入表格.
<div class="codetitle"><a style="CURSOR: pointer" data="75935" class="copybut" id="copybut75935" onclick="doCopy('code75935')"> 代码如下:

<div class="codebody" id="code75935">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">



<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="submit.js" language="javascript">


Insert 知识点
<form name="insertForm">
<label for="question">知识点
<input name="question" type="text"/>



<label for="answer"> 答案
<input name="answer" type="text"/>




<input name="confirm" value="添加" type="button" onclick="getValue();">




需要js来处理提交数据到服务器上以及从服务器获取提交后的返回数据. submit.js代码如:
<div class="codetitle"><a style="CURSOR: pointer" data="67649" class="copybut" id="copybut67649" onclick="doCopy('code67649')"> 代码如下:
<div class="codebody" id="code67649">
/
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处理界面,负责跟服务器交换数据
<div class="codetitle"><a style="CURSOR: pointer" data="45622" class="copybut" id="copybut45622" onclick="doCopy('code45622')"> 代码如下:
<div class="codebody" id="code45622">
<?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 "输入成功";
?>

ajaxphp写入数据库

猜你在找的Ajax相关文章