ajax php 实现写入数据库

yipeiwu_com5年前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 "输入成功";
?>

相关文章

php生成图片缩略图的方法

本文实例讲述了php生成图片缩略图的方法。分享给大家供大家参考。具体如下: 这里需要用到GD2 library function make_thumb($src,$dest,$des...

php自动加载的两种实现方法

php自动载方法有两种. 第一种方案用__autoload,这个函数较简单,也较弱. 但有一问题没有解决, 就是在include前判断文件是否存在的问题. 复制代码 代码如下: set_...

php中分页及SqlHelper类用法实例

php中分页及SqlHelper类用法实例

本文实例讲述了php中分页及SqlHelper类用法。分享给大家供大家参考,具体如下: 文档目录结构如下: SqlHelper.php代码如下: <?php /**...

php 无限分类的树类代码

复制代码 代码如下:<?php /** by lenush; */ class Tree { var $data = array(); var $child = array(-1=...

PHP中exec与system用法区别分析

本文实例讲述了PHP中exec与system用法区别,分享给大家供大家参考之用。具体方法如下: 一般来说,在PHP中调用外部命令,可以用exec及system来实现: system()...