jQuery中实现Ajax小案例

需求:引入jquery实现根据图书编号查询对应图书
前台代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>jq框架Ajax相关API</title>
	<script src="jquery.js"></script>
	<script>
	$(function(){
		$("#btn").click(function(){
			var code = $("#code").val();
			$.ajax({
				type:'get',
				url:'04.php',
				data:{code:code},
				dataType:'json',
				success:function(data){
					if(data.flag == 0){
						$("#box").text('没有该编号书籍');
					}else{
						var tag = '<ul><li>书名:'+ data.bookname +'</li><li>'+ data.author +'</li></ul>'
						$("#box").html(tag);
					}
				},
				error:function(){
					$("#box").html("服务器端错误");
				}
			});
		});
	});
	</script>
</head>
<body>
	请输入图书编号:<input type="text" id="code" name="code">
	<input type="button" value="查询" id="btn">
	<div id="box"></div>
</body>
</html>

后台代码:

<?php 
	$code = $_GET['code'];
	$arr = array();
	$arr[1] = array("bookname"=>"西游记","author"=>"吴承恩");
	$arr[2] = array("bookname"=>"三国演义","author"=>"罗贯中");
	$arr[3] = array("bookname"=>"水浒传","author"=>"施耐庵");
	$arr[4] = array("bookname"=>"红楼梦","author"=>"曹雪芹");
	if(array_key_exists($code, $arr) == 1){//用来判断数组中是否有对应键
		echo json_encode($arr[$code]);
	}else {
		echo '{"flag":"0"}';
	}
 ?>

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43537987/article/details/89219942