php+ajax+json

来个例子:(json.html)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/jquery.js"></script>
</head>
<body>
<input type="button" value="submit" id="submit">
<div id="txt">&</div>
<script>
//监听对象
document.getElementById('submit').onclick = function(){
  post("json.php","name=复读机1&age=123",function(data){
    console.log(data);
  },"json")
}
//简单的post封装
function post(url,data,callback,dataType){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      callback(JSON.parse(xhr.responseText));
    }
  }
  xhr.open("post",url,true);
  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
  xhr.send(data);
}
</script>
</body>
</html>

json.php

<?php
$info = array("name"=>"复读机2","age"=>223);
$infoencode = json_encode($info);//转化为json格式
echo $infoencode;
?>

如果php文件是gb2312格式,把变量值转化为utf-8格式的,因为json_encode函数的参数必须是utf-8:

<?php
$info = array("name"=>"复读机2","age"=>223);
foreach($info as $name => $value){
    $infogb["$name"] = iconv('gb2312','utf-8',$value);
}
$infoencode = json_encode($infogb);
echo $infoencode;
?>

总结一下:前端向后端请求发送的数据还是查询字符串格式,而后端向前端响应的数据为json格式以便于用javascript解析。

posted on 2015-05-20 22:00  复读机  阅读(738)  评论(0编辑  收藏  举报

导航