ajax php 实现写入数据库

yipeiwu_com6年前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.ini,首先找到 ;;;;;;;;;;;;;;;; ; file uploads ; ;;;;;;;;;;;;;;;; 区域,有影响文件上传的以下几个参数: file...

PHP中有关长整数的一些操作教程

PHP中有关长整数的一些操作教程

前言 在PHP,数字类型只有int和float两种,它们的位数取决于系统,而且没有uint,所以跟其它系统通信的时候就有诸多不便。如果int溢出,则自动转换为float,用科学计数法来表...

php时间不正确的解决方法

2。date_default_timezone_set("PRC");    3。PHP   5.1以上  ...

dede3.1分页文字采集过滤规则详说(图文教程)续四

dede3.1分页文字采集过滤规则详说(图文教程)续四

至此,分页内容匹配进行完毕。  文章内容匹配、分页内容匹配都进行完后,最后就只有“过滤”了,包括分页区域过滤和文章内容过滤。据本人的感觉,上面的两个规则都好写,只要找到全部链接...

PHP将二维数组某一个字段相同的数组合并起来的方法

本文实例讲述了PHP将二维数组某一个字段相同的数组合并起来的方法。分享给大家供大家参考,具体如下: 例子: array(3) { [0]=> array(16) { [...