PHP+ajax

搞了一天左右,其间真的是各种坑,现在记录一下,希望看到的能够避坑


写代码之前,要先搭环境,我使用的phpstudy,简单方便,至于怎么安装,网上教程很多,这里就多说了

<html>
<head>
<script type="text/javascript" src="jquery-3.0.0.js"></script>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
 
<script type="text/javascript">

function ajax(){

  
if (window.XMLHttpRequest)
{

// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行的代码
xmlhttp=new XMLHttpRequest();
}
else
{
//IE6, IE5 浏览器执行的代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{


alert("xmlhttp.status=="+xmlhttp.status);




if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("xmlhttp.readyState==4 && xmlhttp.status==200");
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","query.php",true);

xmlhttp.send();
}
</script>
</head>


<body>


<input type="button" value="点击" onclick="ajax();">
</body>


</html>


//这里本来是使用jquery的ajax,但是试了很多遍多没用,所以,,,,,,,,,,,



PHP文件

<?php
    printf("进入后台");
    header('Content-Type: application/json');
header('Access-Control-Allow-Origin:*');  
header('Content-Type:text/html; charset=gb2312');
    // 实例化mysqli类
    $mysqliConn = new mysqli();
 
    // 连接服务器,并选择一个数据库
    // 错误的密码,分别是服务器地址,用户名,密码,数据库名
    $mysqliConn->connect('********************', 'root', 'root', 'cxn');
    if ($mysqliConn->connect_error)
    {
        printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
        exit();
    }
    
    // 与数据库交互
    $query = 'select username,age,password,email from user;';
 
    $result = $mysqliConn->query($query);


 





//echo json_encode($result);
    // 迭代处理结果集
  //  while (list($username, $age, $password,$email) = $result->fetch_row())
 // {
      //printf("name:%s  age:%s password:%s email:%s<br/>", $username, $age, $password,$email);


 // echo("name:"+$username+  "age:"+$age"password:"+$password +"email:"+$email);


// }


     while($row=$result->fetch_object()){
     echo json_encode($row);
          
        }
    
    // 关闭连接
    $mysqliConn->close();
?>

这里写好后,就是访问了,,把2个文件都放入PHP服务器下,这里的PHP服务器是在你安装PHPstudy的时候,选择的路径,放进去之后,,记住,智力不能直接打开这个HTML去访问,必须经过http://localhost/t.html,我就是在这里被坑了,如果直接右键访问这个HTML,返回的是PHP文件的所有代码,所以这里要注意一下啊


猜你喜欢

转载自blog.csdn.net/u013401913/article/details/52964226