Ajax的三种返回类型
**一.TEXT
*二.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="../../jquery-1.11.2.min.js"></script>
</head> <body>
</body>
<script type="text/javascript"> $(document).ready(function(e) { $.ajax({
url:"Untitled-4.php",
data:{},
dataType:"JSON",
type:"POST",
success: function(data){ /* for(key in data)
{
alert(data[key].Name);
}*/ for(var i=0;i<data.length;i++)
{
alert(data[i].Name);
} } }); }); </script>
</html>
处理页面代码:
<?php include("JsonQ.php");
$db = new JsonQ(); $sql = "select * from Nation"; echo $db->JsonQuery($sql);
调用Ajax返回JSON数据类型的方法封装成类,应用的是pdo能比较方便的返回所有数据的关联数组
<?php
class JsonQ
{
public $host = "localhost";//服务器地址
public $uid = "root"; //数据库的用户名
public $pwd = "101213"; //数据库的密码 //Ajax调用返回JSON
public function JsonQuery($sql,$type=1,$db="lian1")
{
//定义数据源
$dsn = "mysql:dbname={$db};host={$this->host}";
//造pdo对象
$pdo = new PDO($dsn,"{$this->uid}","{$this->pwd}"); //准备执行SQL语句
$st = $pdo->prepare($sql); //执行预处理语句
if($st->execute())
{
if($type==1)
{
$attr = $st->fetchAll(PDO::FETCH_ASSOC);
return json_encode($attr);
}
else
{
if($st)
{
return "OK";
}
else
{
return "ON";
}
}
}
else
{
echo "执行失败!";
}
} }
图示:
三.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="../../jquery-1.11.2.min.js"></script>
</head> <body>
</body>
<script type="text/javascript"> $(document).ready(function(e) { $.ajax({
url:"Untitled-4.php",
data:{},
dataType:"XML",
type:"POST",
success: function(data){ alert($(data).find("Code").eq(0).text());//eq是取某一个数据 } }); }); </script>
</html>
处理页面:
<?php
header("Content-type:text/html;charset=utf-8");
$str = <<<GD
<Info>
<n1>
<Code>n001</Code>
<Name>什么</Name>
<Sex>男</Sex>
</n1>
<n2>
<Code>n002</Code>
<Name>哎哟</Name>
<Sex>男</Sex>
</n2>
</Info>
GD;
echo $str;
XML的特点:
1.有且只有一个根
2.大小写敏感
3.标签必须前后呼应,成对存在(就是要写完整)
4.标签名可以自定义,开始标签里面可以写属性,属性名也可以自定义