码迷,mamicode.com
首页 > Web开发 > 详细

Ajax之get请求

时间:2017-06-09 18:14:18      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:代码   engine   att   encode   primary   host   fetch   exce   use   

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>get</title>
    <script src="./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 = {"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请求

标签:代码   engine   att   encode   primary   host   fetch   exce   use   

原文地址:http://www.cnblogs.com/htmlphp/p/6973012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!