$.ajax()方法从服务器获取json数据

感谢各位CSDN的大神,自己参照着捣鼓了一天,终于完整的串联起来了

html以及jQuery ajax部分

========================================================================

<button id="sub">查询所有数据</button>

        <!-- 用以显示返回来的数据,只刷新这部分地方 -->
    <div id="text" style="color:red;width:500px;height:200px;border:1px solid green;">数据库返回的数据</div>

$('#sub').click(function(){

      
      $.ajax({
        type: "post",
        url: "getListTop10.php",
        data:{username:'demo'},//提交到demo.php的数据
        dataType: "json",//回调函数接收数据的数据格式
        success: function(msg){
         $('#text').empty();   //清空Text里面的所有内容
   
         var json="";
         for(var i=0;i<msg.length;i++)
         {
          json+=("id是" + msg[i].id + "username是" + msg[i].username + "password是" + msg[i].password +"sex是" + msg[i].sex + "<br>");
         }
         $('#text').html(json);
          console.log(msg);
        },
        error:function(msg){
        $('#text').html("<span>"+"失败!..."+"</span>")
          console.log(msg);
        }
      });

    })

=====================================================================

php部分

<?php  
header("Content-type:text/html;charset=utf-8");
$host='localhost';//主机  
$user='root';//数据库账号  
$password='034859';//数据库密码  
$database='login';//数据库名  
$tablename='user';//数据库中名为listtop的表  
mysql_connect("localhost","root","034859") or die("error");//连接数据库管理系统  
mysql_select_db("login");//选择操作数据库  
mysql_query("SET NAMES utf8");//设置设置UTF-8编码(JSON的唯一编码),数据库整理为:utf8_general_ci,以此达到输出中文简体的目的  
  
/*导数据库中查询,通过$_POST*/
$username = $_POST['username'];//ajax中的data参数用同名变量接收  
$returnData=mysql_query("SELECT * FROM user");  //查询出表名为user内所有的内容
 
while($result=mysql_fetch_assoc($returnData)){  
    $listTop_info[]=$result;//将取得的所有数据,一行两行或者三行,此例只有一行,赋值给listTop_info数组  
}  
echo json_encode($listTop_info);//将listTop_info数组转换成json数组

?> 

数据库部分


运行环境是用的wampserver


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值