PHP利用Ajax连接到数据库
直接亮出来代码好了 这个是一个添加文章类别功能的页面
sortadd.php
<script language="javascript">
var http_request=false;
function createRequest(url){
http_request=false;
if(window.XMLHttpRequest){
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType){
http_request.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
try{
http_request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(!http_request){
alert("不能创建XMLHTTP实例!");
return false;
}
http_request.onreadystatechange=alertContents;
http_request.open("GET",url,true);
http_request.send(null);
}
function alertContents(){
if(http_request.readyState==4){
if(http_request.status==200){
sort_id.innerHTML=http_request.responseText;
}else{
alert('您请求的页面发现错误!');
}
}
}
</script>
<script>
function checksort(){
var txt_sort=form1.txt_sort.value;
if(txt_sort==""){
window.alert("请填写文章类别!");
form1.txt_sort.focus();
return false;
}else{
createRequest('checksort.php?txt_sort='+txt_sort);
}
}
</script>
<td width="14%" valign="baseline" id="sort_id">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td><form action="" name="form1" method="get"><select name="select">
<?php
$link=mysql_connect("localhost","root","8346322");
mysql_select_db("wp",$link);
$GB2312string=iconv('UTF-8','gb2312//IGNORE',$RequestAjaxString);
mysql_query("set names gb2312");
$sql=mysql_query("select distinct * from wp_jargon group by jargon_text");
$result=mysql_fetch_object($sql);
do{
header('Content-type:text/html;charset=GB2312');
?>
<option value="<?php echo $result->jargon_text;?>" selected><?php echo $result->jargon_explain;?></option>
<?php
}while($result=mysql_fetch_object($sql));
?>
</select>
</td>
<td width="20%" height="21" align="right" valign="baseline">
<input name="txt_sort" type="text" id="txt_sort" size="12" style="border:1px #64284A solid; height:21">
</td>
<td width="49%" height="21" align="left" valign="baseline">
<input type="button" value="提交"onclick="checksort();">
</td>
</form>
</tr>
</table>
</td>
然后是checksort.php
<?php
/*
添加分类信息处理页checksort.php
*/
$link=mysql_connect("localhost","root","8346322");
mysql_select_db("wp",$link);
$GB2312string=iconv('UTF-8','gb2312//IGNORE',$RequestAjaxString);
mysql_query("set names gb2312");
$sort=$_GET[txt_sort];
mysql_query("insert into wp_jargon(jargon_text) values('$sort')");
&nb