服务器向ajax回送数据的3种格式:文本格式、xml、json

本文介绍了服务器如何以三种不同格式(文本、XML、JSON)回送数据给Ajax引擎。通过PHP示例,详细展示了在接收到Ajax请求后,如何处理数据并以特定格式响应,包括文本格式的简单回送,XML格式的结构化数据,以及JSON格式的复杂数据结构。同时,文中涉及到内容类型设置、文件记录以及条件判断来验证数据接收与处理。

第三根线:服务器接收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;

?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值