Ajax实现不刷新取最新商品
话不多说,请看代码:
<?php
$conn=mysql_connect('localhost','root','123456')ordie('连接失败');
mysql_select_db('ecshop');
mysql_query('setnamesutf8');
$attr=isset($_GET['attr'])?$_GET['attr']:'is_hot';//由html的ajax提交过来然后根据它来取数据~
$sql='selectgoods_name,goods_id,shop_pricefromgoodswhere'.$attr.'=1limit0,3';
$rs=mysql_query($sql,$conn);
//var_dump($rs);
$goods=array();
while($row=mysql_fetch_assoc($rs)){
$goods[]=$row;
}
//print_r($goods);
?>
<tableborder='1'>//ajax接收的就是php输出内容虽然它没echo但也是输出在网页的内容所以ajax能接收~~!!!
<tr><td>商品ID</td><td>商品名称</td><td>商品价格</td></tr>
<?phpforeach($goodsas$v){?>
<tr>
<td><?phpecho$v['goods_id'];?></td>
<td><?phpecho$v['goods_name'];?></td>
<td><?phpecho$v['shop_price'];?></td>
</tr>
<?php}?>
</table>
HTML的内容
<script>
varxhr=newXMLHttpRequest();
functiontop3(attr){
varurl='goods.php?attr='+attr;
xhr.open('get',url);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
vardobj=document.getElementsByTagName('div')[0].innerHTML=xhr.responseText;//把从php接收的内容放入INNERHTML
}
}
xhr.send();
}
</script>
</head>
<body>
<inputtype="button"value="最新商品"onclick="top3('is_new');">
<inputtype="button"value="热卖商品"onclick="top3('is_hot');">
<inputtype="button"value="精品商品"onclick="top3('is_best');">
<divid="test">
</div>
</body>
实例2:根据输入的ID获取商品信息并修改
<?php
$conn=mysql_connect('localhost','root','123456')ordie('连接失败');
mysql_select_db('ecshop');
mysql_query('setnamesutf8');
$id=isset($_GET['id'])?$_GET['id']:1;
if($id==''){
$error['num']=1;
$error['msg'];
}
$sql='selectgoods_id,goods_name,shop_price,goods_numberfromgoodswheregoods_id='.$id;
$rs=mysql_query($sql);
if(!($goods=mysql_fetch_assoc($rs))){//获取不到商品就返回false
echo'没有该商品!';
exit;
}
echojson_encode($goods);//把数组转成一个json格式~~
?>
HTML端的内容
<script>
varxhr=newXMLHttpRequest();
functionmodify(){
varinputs=document.getElementsByTagName('input')
vargid=inputs[0].value;
varurl='search.php?id='+gid;
xhr.open('get',url);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
vardata=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:<inputtype="text"name="goods_id"onfocus="al()"onblur="modify();"/><br/><span></span>
商品名称:<inputtype="text"name="goods_name"/><br/>
商品库存:<inputtype="text"name="goods_number"/><br/>
商品价格:<inputtype="text"name="shop_price"/><br/>
<inputtype="submit"value="修改"/>
</body>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!