Ajax实现不刷新取最新商品
更新:HHH   时间:2023-1-8


话不多说,请看代码:

<?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 border='1'> //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="最新商品" onclick="top3('is_new');"> 
  <input type="button" value="热卖商品" onclick="top3('is_hot');"> 
  <input type="button" value="精品商品" onclick="top3('is_best');"> 
  <div id="test"> 
  </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> 
<h2>商品编辑</h2> 
  商品id:<input type="text" name="goods_id" onfocus="al()" onblur="modify();" /><br /> <span></span> 
  商品名称:<input type="text" name="goods_name" /><br /> 
  商品库存:<input type="text" name="goods_number" /><br /> 
  商品价格:<input type="text" name="shop_price" /><br /> 
  <input type="submit" value="修改" /> 
</body>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持天达云!

返回web开发教程...