首页 > 资讯列表 > 编程/数据库 >> PHP

ajax php 实现写入数据库

PHP 2014-11-28 23:53:47 转载来源: 网络整理/侵权必删

本文为大家讲解的是php+ajax实现的写入数据库示例,感兴趣的同学参考下. <!-- To change this template, choose Tools | Templates and open the template in the editor

本文为大家讲解的是php+ajax实现写入数据库示例,感兴趣的同学参考下.


<!--
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 "输入成功";
?>

 


标签: ajax php 实现 写入 数据库


声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!

站长搜索

http://www.adminso.com

Copyright @ 2007~2024 All Rights Reserved.

Powered By 站长搜索

打开手机扫描上面的二维码打开手机版


使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

站长搜索目录系统技术支持