【问题标题】:Return json on exit php在退出 php 时返回 json
【发布时间】:2013-05-18 18:44:06
【问题描述】:

我一直在使用$.getJSON 来验证脚本是否正确地完成了它的工作,使用exit("{'status':true}")(或错误)但现在我需要脚本返回一个值(或一个数组)。我看到我不能使用exit('{ "status": $myarray}');。我可以用什么代替?我是 php 新手-是否可以做类似return '{ "status": $myarray}'; 或类似的事情? 提前致谢

【问题讨论】:

    标签: php jquery ajax json return


    【解决方案1】:

    您可以使用以下功能:

    json_encode($data);
    

    见: http://php.net/manual/en/function.json-encode.php

    【讨论】:

    • 然后退出($data)? ajax 将如何接收响应?
    【解决方案2】:

    在你的 php 中,使用 json_encode 这样:

    <?php
        header('Content-Type: application/json');
        echo json_encode($myarray);
        // or, `exit(json_encode($myarray))` if global scope (see *REF)
    ?>
    

    在你的 jQuery 中通常使用getJSON

    $.getJSON("test.php",function(result){
        ...
    });
    

    (*) 参考号:PHP - exit or return which is better?

    【讨论】:

      【解决方案3】:

      如果你想返回数据,就像 json 中的数组或单个数据,那么 试试这个代码

      在php文件中这样写

      $value = 'welcome';
      echo json_encode($value);exit;
      
      or
      
      $value = array("Saab","Volvo","BMW","Toyota");
      print_r(json_encode($value));exit;
      

      【讨论】:

        【解决方案4】:
           `$jsonString = 'your json string'`
            $jsonArray = json_encode($jsonString);
            return $jsonArray
        

        【讨论】:

        • 我认为问题是关于编码而不是解码。
        【解决方案5】:

        我会按照我的方式发布,现在对我来说似乎很简单。谢谢你的回答

        $json_array=array('status'=>$row);
        exit(json_encode($json_array));
        

        AJAX 调用:

           $.getJSON( "savefunctions/getVideos.php", function(response) {
                                 if( response.status ) alert(response.status);
                                 });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-29
          • 2011-10-02
          • 2017-01-08
          • 1970-01-01
          • 1970-01-01
          • 2017-02-12
          相关资源
          最近更新 更多