Ajax实现不刷新取最新商品

话不多说,请看代码:

<?php $conn = mysql_connect('localhost','root','123456') or die('连接失败'); mysql_select_db('ecshop'); mysql_query('set names utf8'); $attr = isset($_GET['attr'])?$_GET['attr']:'is_hot'; //由html 的ajax提交过来 然后根据它来取数据~ $sql = 'select goods_name,goods_id,shop_price from goods where '.$attr.' = 1 limit 0,3'; $rs = mysql_query($sql,$conn); //var_dump($rs); $goods = array(); while($row = mysql_fetch_assoc($rs)){ $goods[] = $row; } //print_r($goods); ?>

<table> //ajax 接收的就是 php输出内容 虽然它没echo 但也是输出在网页的内容 所以ajax 能接收~~!!! <tr><td>商品ID</td><td>商品名称</td><td>商品价格</td></tr> <?php foreach($goods as $v){ ?> <tr> <td><?php echo $v['goods_id'];?></td> <td><?php echo $v['goods_name'];?></td> <td><?php echo $v['shop_price'];?></td> </tr> <?php }?> </table>

HTML 的内容

<script> var xhr = new XMLHttpRequest(); function top3(attr){ var url = 'goods.php?attr=' + attr; xhr.open('get',url); xhr.onreadystatechange = function (){ if(xhr.readyState ==4){ var dobj = document.getElementsByTagName('div')[0].innerHTML = xhr.responseText; //把从php 接收的内容放入INNERHTML } } xhr.send(); } </script> </head> <body> <input type="button" value="最新商品"> <input type="button" value="热卖商品"> <input type="button" value="精品商品"> <div> </div> </body>

实例2:根据输入的ID 获取商品信息 并修改

<?php $conn = mysql_connect('localhost','root','123456') or die('连接失败'); mysql_select_db('ecshop'); mysql_query('set names utf8'); $id = isset($_GET['id'])?$_GET['id']:1; if($id==''){ $error['num'] = 1; $error['msg']; } $sql = 'select goods_id,goods_name,shop_price,goods_number from goods where goods_id ='.$id; $rs = mysql_query($sql); if(!($goods = mysql_fetch_assoc($rs))){ //获取不到商品就返回false echo '没有该商品!'; exit; } echo json_encode($goods); //把数组转成一个json 格式~~ ?>

HTML端的内容

<script> var xhr = new XMLHttpRequest(); function modify(){ var inputs = document.getElementsByTagName('input') var gid = inputs[0].value; var url = 'search.php?id='+ gid; xhr.open('get',url); xhr.onreadystatechange = function (){ if(xhr.readyState ==4){ var data = eval('('+ xhr.responseText +')') //把接收到的json 格式数据转成JS的对象! inputs[1].value = data.goods_name; inputs[2].value = data.goods_number; inputs[3].value = data.shop_price; } } xhr.send(null) //经常漏写了~~~不写是发送不了请求的~~一定要写! } </script> </head> <body> <h1>商品编辑</h1> 商品id:<input type="text" onfocus="al()" onblur="modify();" /><br /> <span></span> 商品名称:<input type="text" /><br /> 商品库存:<input type="text" /><br /> 商品价格:<input type="text" /><br /> <input type="submit" value="修改" /> </body>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzzxp.html