Ajax之get請求
阿新 • • 發佈:2017-06-09
reat col pwd click incr har auto blog 連接數據庫
<!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請求