首页 > 代码库 > ajax 另外两种返回类型(json xml)

ajax 另外两种返回类型(json xml)

返回json类型(例子):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://www.mamicode.com/jquery-1.11.2.min.js"></script>
</head>

<body>

<select id="nation">
	
</select>

<script type="text/javascript">

$.ajax({
		url:"jsonchuli.php",
		dataType:"JSON",
		success: function(data){
				var str ="";
				/*for(var i=0;i<data.length;i++)
				{
					str = str+"<option value=http://www.mamicode.com/‘"+data[i].Code+"‘>"+data[i].Name+"</option>";
				}*/
				
				for(var s in data)
				{
					str = str+"<option value=http://www.mamicode.com/‘"+data[s].Code+"‘>"+data[s].Name+"</option>";
				}
				
				$("#nation").html(str);
			}
	});

</script>
</body>
</html>

  

<?php
include("../DBDA.class.php");
$db = new DBDA();

$sql = "select * from nation";

//需要关联数组
//数组内容的编码格式:utf8的

echo json_encode($db->GuanQuery($sql));

  返回xmL类型(例子):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://www.mamicode.com/jquery-1.11.2.min.js"></script>
</head>

<body>

<select id="sel">
</select>

<script type="text/javascript">
$.ajax({
		url:"xmlchuli.php",
		dataType:"XML",
		success: function(data){
				//alert($(data).find("code").eq(1).text());
				alert($(data).find("nation").attr("bs"));
				
				var allcode = $(data).find("code");
				var allname = $(data).find("name");
				var str ="";
				for(var i=0;i<allcode.length;i++)
				{
					var code = allcode.eq(i).text();
					var name = allname.eq(i).text();
					
					str = str +"<option value=http://www.mamicode.com/‘"+code+"‘>"+name+"</option>";
				}
				
				$("#sel").html(str);
			}
	});
</script>
</body>
</html>

  

<?php
include("DBDA.class.php");
$db = new DBDA();

$sql = "select * from nation";

$attr = $db->Query($sql);

echo "<nation bs=‘1‘>";
	
foreach($attr as $k=>$v)
{
	echo "<n{$k}><code>{$v[0]}</code><name>{$v[1]}</name></n{$k}>";
}
	
echo "</nation>";

  

ajax 另外两种返回类型(json xml)