phpajax高级篇

         学ajax到一定程度了,就会要操作数据库了。操作数据库就会遇到编码问题,昨天就遇到了这个问题。搞了一下午都没搞定,知道是编码问题。但不知道怎么解决。搞软件开发什么都不怕,就怕遇到问题,不知道错在那里。一般都不会出现方法的错误。这就要求我们要细心了,这样才能发现问题的所在。

下面就和大家分享一下ajax操作数据库,进行数字,字母,中文的查询。数据库是mysql,语言php.

实例:

page1:phpajax.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
php____ajax
</title>
</head>
<body>

<script language="javascript">
function check()  {
var username=document.getElementById("username");
var url = "phpajax_cl.php?username=" + encodeURI(username.value);
 
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

 xmlHttp.open('GET', url, true);
 xmlHttp.onreadystatechange = function(){
 if (xmlHttp.readyState == 4) {
 //alert(xmlHttp.responseText);
document.getElementById("show").innerHTML =decodeURI(xmlHttp.responseText);
}
 
 }
 xmlHttp.setRequestHeader("Content-Type","text/html;charset=utf-8");
 xmlHttp.send(null);
}


</script>
<form name="form1"  action="" method="post">
<table width="100%" cellspacing="0" cellpadding="0">
  <tr>
    <th scope="row">用户名:<span id="show"></span></th>
    <td><input type="text" id="username" name="username" value=""></td>
    <td><input type="button"  value="唯一性检查" onclick="check()"></td>
    <td></td>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td><input type="submit" name="Submit2" value="提交" /></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</form>

</body>

</html>

page2:phpajax_cl.php

<?php
@header("Content-Type: text/html; charset=utf-8");
$username =urldecode($_GET["username"]);
$conn=mysql_connect('localhost','root','fkedwgwy')
  or  die('连接失败:'.mysql_error());
 
  mysql_query("set names utf8");
//选择数据表
if (mysql_select_db('luowei',$conn))
  {
  
  }
  else
  {
  echo'数据库选择失败!'.mysql_error().'<p>';
  }
   
        //解决数据乱码问题
        $strsql="select * from news where news_title='".$username."'";
        $result=mysql_query($strsql);
        $rows=mysql_num_rows($result);
       
       
        //判断是否有此记录
        if($rows!=0){
            echo "已被注册!".$username;
        }else{
            echo "此用户名未被注册!".$username;
        }
        mysql_close($conn);
?>

希望对初学者有用。

就写到这里了,其它的自己去想吧!

原文地址:https://www.cnblogs.com/fengju/p/6174158.html