JS和PHP之间以JSON格式传输

原文链接: https://www.mk2048.com/blog/blog.php?id=h02b1ba2k1ab&title=JS%E5%92%8CPHP%E4%B9%8B%E9%97%B4%E4%BB%A5JSON%E6%A0%BC%E5%BC%8F%E4%BC%A0%E8%BE%93

Json是一种的轻量级文本数据交换格式。它独立于编程语言,可以用于在不用的编程语言之间进行数据的交互。

下面简单例举二个使用JSON进行数据通信的例子。

第一个例子:

//Javascript以ajax发送数据JSON数据,PHP接收JSON
//前端
var arr ={
    "name":"小明",
    "age":16
    };
var json =JSON.stringify(arr);//使用JSON将对象转换成JSON格式数据
var xhr = new XMLHttpRequest;
xhr.open('post', './bb.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("user="   json);//  Content-Type设置成application/x-www-form-urlencoded 的情况下,请求主体可以用key1=value1&key2=value2的形式发送数据
xhr.onreadystatechange = function() {
         if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status ==304))  //响应完成并且响应码为200或304
         alert(xhr.responseText);
}
------华丽的分割线----------------------------------------------------
//后端 <?php $info = $_POST["user"]; // 这个时候的info是一个字符串 $result = json_decode($info); // 这个时候的result已经被还原成对象 echo $result -> name;

第二个例子:

//PHP发送数据JSON数据   Javascript以ajax接收JSON
//前端
var xhr = new XMLHttpRequest;
xhr.open('post', './bb.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send();
xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status ==304)) { //响应完成并且响应码为200或304
        var rst = JSON.parse(xhr.responseText);    
        alert(rst.name);    
    }
};
------华丽的分割线----------------------------------------------------
//后端 
$info = array("lession" => "English", "name"=>"Lily");
echo json_encode($info);

补充一个关于JSON的兼容。JSON这个内置对象在IE8之前是不存在的,如果在IE8之前需要使用JSON对象,需要像下述一样引入一个第三方插件json2.js。这样IE7及以下版本就会加载json2.js插件,而其他浏览器或者8及以上版本的IE则不会加载这个插件:

<!--[if lte IE 7]>    
   <script src="./json2.js"></script>
<![endif]-->

更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/whiteGay/article/details/102757266