首页 > 代码库 > Ajax之get请求

Ajax之get请求

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>get</title>
    <script src="http://www.mamicode.com/js/jquery.min.js"></script>
</head>
<body>
    <div id="box"></div>
    <button id="1">国内新闻</button>
    <button id="2">国外新闻</button>
</body>
<script>
    $("button").click(function(){
        var typeId = $(this).attr("id");
        var data = http://www.mamicode.com/{"typeId":typeId}; //typeId={typeId}
        
        $.get("./a1.php",data,function(d){
            var html = "";
            for(var i in d){
                html += d[i].title+"<br/>";
            }
            $("#box").html(html);
        },"json");
    });
</script>
</html>

2. php代码
<?php
//1.连接数据库
try{
    $dsn = "mysql:host=localhost;dbname=jkxy";
    $username = "root";
    $pwd = "";
    $pdo = new PDO($dsn,$username,$pwd);
}catch (PDOException $e){
    echo $e -> getMessage();
}

//2.查询数据库
try{
    $typeId = $_GET[‘typeId‘];
    $sql = "SELECT * FROM news WHERE typeId = {$typeId}";
    $stmt = $pdo -> query($sql);
    $news = $stmt -> fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($news);
}catch(PDOException $e){
    echo $e -> getMessage();
}
?>

3. 建表代码
CREATE TABLE `news` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL DEFAULT ‘‘,
  `content` text NOT NULL,
  `typeId` int(11) NOT NULL DEFAULT ‘0‘,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=utf8

 

Ajax之get请求