05 js利用ajax向服务器发送请求并返回json值
创建一个php
$json = '';
$data = array();
$con =mysqli_connect($servername, $username, $password, $dbname);//连接服务器
class User
{
public $name;
public $chengji;
}
$sql = "SELECT * FROM xxxx";//获取数据库列表
$result = $con->query($sql);
if($result){
//echo "查询成功";
while ($row = mysqli_fetch_array($result))
{
$user = new User();
$user->name = $row["name"];
$user->chengji = $row["chengji"];
$data[]=$user;
}
$json = json_encode($data);//把数据转换为JSON数据.
echo "$json";
}else{
echo "查询失败";
}
?>
ajax获取json数据
var settings = {
"url": "php在服务器的地址",
"method": "GET",//用get请求服务器
"timeout": 0,
dataType: "json",//数据类型为json
};
$.ajax(settings).done(function (response) {
var json = response;
for (var index in json) {
console.log(json[index].属性, " ", json[index].属性2);
};
console.log(response);
});