Ajax 实现不刷新取最新商品

前端之家收集整理的这篇文章主要介绍了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 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','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" 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>

猜你在找的Ajax相关文章