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 HtmlReplace输入过滤安全函数

复制代码 代码如下: // $rptype = 0 表示仅替换 html标记 // $rptype = 1 表示替换 html标记同时去除连续空白字符 // $rptype = 2 表示...

PHP微信公众号开发之微信红包实现方法分析

本文实例讲述了PHP微信公众号开发之微信红包实现方法。分享给大家供大家参考,具体如下: 这几天遇到了一个客户 要给他们的微信公众平台上添加微信现金红包功能,是个二次开发的功能,顺手百度一...

PHP防止表单重复提交的几种常用方法汇总

本文较为详细的汇总了PHP防止表单重复提交的几种常用方法,在PHP程序开发中有着很高的实用价值。具体方法如下: 1. 使用JS让按钮在点击一次后禁用(disable)。采用这种方法可以防...

php代码调试利器firephp安装与使用方法分析

php代码调试利器firephp安装与使用方法分析

本文实例分析了php代码调试利器firephp安装与使用方法。分享给大家供大家参考,具体如下: firephp简述 如果你曾经写过js代码的话,那么你对如下的代码肯定不会陌生: co...

php xfocus防注入资料

这里没有太深的技术含量,我只是比较简单的谈了谈。(以下操作如无具体说 明,都是基于PHP+MySQL+Apache的情况) 在现在各种黑客横行的时候,如何实现自己ph...