第三根线:服务器接收ajax发送来的数据,对其进行处理(操作数据库),然后将处理后的数据返回给ajax引擎对象,返回数据的格式有3种:文本格式、 xml、 json;
文本格式:header(“content-type:text/html;charset=utf-8”);
xml格式:header(“content-type:text/xml;charset=utf-8”);
json格式:header(“content-type:text/html;charset=utf-8”);
文本格式:
<?php
header("content-type:text/html;charset=utf-8");
header("cache-control:no-cache");
$username = $_POST['username'];
//因为echo语句直接将数据会送给ajax,而不是直接显示在页面中,所以使用文件的方式验证服务器端是否接收到了ajax传送过来的数据。
file_put_contents("D:/wamp/www/ajax/mylog.log",$username."\r\n",FILE_APPEND);
if ($username == "xuting")
{
echo "用户名已存在";
} else {
echo "用户名可用";
}
?>
xml格式:
<?php
header("content-type:text/xml;charset=gbk");
header("cache-control:no-cache");
$province = $_POST['province'];
file_put_contents("D:/wamp/www/ajax/mylog.log",$province."\r\n",FILE_APPEND);
$info = "";
if ($province == "shanxi"){
$info ="<province><city>西安市</city><city>渭南市</city></province>";
} else if ($province =="yunnan"){
$info ="<province><city>昆明市</city><city>丽江市</city></province>";
} else if ($province =="sichuan"){
$info ="<province><city>成都市</city><city>绵阳市</city></province>";
}
echo $info;
?>
json格式:
<?php
header("content-type:text/html;charset=utf-8");
header("cache-control:no-cache");
$cities = $_POST['city'];
file_put_contents("D:/wamp/www/ajax/mylog.log",$cities."\r\n", FILE_APPEND);
//在服务器端随机产生一些价格数据,并以json格式返回数据。
$res = '[';
for ($i = 0; $i < count($cities);$i++)
{
if ($i == count($cities) - 1)
{
$res .='{"cityname":"'.$cities[$i].'","price":"'.rand(500,1500).'"}]';
} else {
$res .='{"cityname":"'.$cities[$i].'","price":"'.rand(500,1500).'"},';
}
}
file_put_contents("D:/wamp/www/ajax/mylog.log",$res."\r\n", FILE_APPEND);
echo $res;
?>