zoukankan      html  css  js  c++  java
  • 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解析。

  • 相关阅读:
    力扣(LeetCode)67. 二进制求和
    力扣(LeetCode) 66. 加一
    力扣(LeetCode)58. 最后一个单词的长度
    力扣(LeetCode)1009. 十进制整数的反码
    力扣(LeetCode) 20. 有效的括号
    力扣(LeetCode)1016. 子串能表示从 1 到 N 数字的二进制串
    数据库索引
    OSI 七层和五层
    ST算法
    F
  • 原文地址:https://www.cnblogs.com/wang-jiang/p/4518325.html
Copyright © 2011-2022 走看看