zoukankan      html  css  js  c++  java
  • php如何返回json数据

    php返回json,xml,JSONP等格式的数据

    返回json数据:

    header('Content-Type:application/json; charset=utf-8');

    $arr = array('a'=>1,'b'=>2);

    exit(json_encode($arr));

    注意:如果不加header直接输出json_encode的值的话,返回的是字符串不是对象,js那边就需要先eval('('+data+')')转化为对象,在取值

       

    返回xml数据:

    header('Content-Type:text/xml; charset=utf-8');

    exit($xml);

       

    返回jsonp数据:

    $arr = array('a'=>1, 'b'=>2, 'c'=>3);

    $json = json_encode($arr);

    $callback = $_GET['callback'];

    exit($callback."($json)");

    //注意callback是js传过来的参数名称

       

    thinkphp如何返回各种数据:

    $this->ajaxReturn (json_encode($arr),'JSON');

    $this->ajaxReturn (json_encode($arr),'JSONP');

    $this->ajaxReturn (json_encode($arr),'XML');

       

    json_encode有个参数禁止unicode编码

    JSON_UNESCAPED_UNICODE

    json_encode('中文',JSON_UNESCAPED_UNICODE);

       

    默认中文编码

    header('Content-Type:application/json; charset=gbk');

    $data = $db->select($sql);
    $data = json_encode($data);
    $data=preg_replace("#\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'gbk', pack('H4', '\1'))", $data);

     exit($data);

  • 相关阅读:
    Visual Studio 2015 密钥
    Vue-next源码新鲜出炉一
    vue2.0基础整理
    Nest
    Nest
    Nest
    Nest
    Nest快速上手
    element-plus源码分析第一节
    获取视频第一帧,作为封面图
  • 原文地址:https://www.cnblogs.com/lovebing/p/9289076.html
Copyright © 2011-2022 走看看