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中用date函数获取当前时间有误的解决办法

初学PHP做网站,想在页面上获得当前时间,学过编程的人都知道用时间函数date(),先用这个函数格式化一个本地时间/日期,先写个测试代码吧,结果输出时间比实际时间少了8小时,这是什么原因...

PHP反射API示例分享

本文实例为大家分享了 PHP反射API--利用反射技术实现的插件系统架构,供大家参考,具体内容如下 <?php /** * @name PHP反射API--利用反射...

PHP 通过Socket收发十六进制数据的实现代码

最近在php下做关于Socket通讯的相关内容,发现网络上好多人在了解如何进行16进制收发,研究了下,代码如下,欢迎拍砖。复制代码 代码如下:<?php  &n...

php生成网页桌面快捷方式

php生成网页桌面快捷方式

本文将介绍使用PHP生成网页桌面快捷方式的代码,并添加图标及解决不同浏览器保存出现的乱码问题。 我们访问网站时,如果网站的内容很有吸引,一般我们都会使用浏览器的收藏夹功能,收藏此网站。...

dede全站URL静态化改造[070414更正]

1、将include复制到网站中的include目录。 2、修改数据库 将所有文档设置为“仅动态”,可以进入数据库管理中,执行下面命令: update dede_archive...