doulao3078 2013-02-26 09:51
浏览 24
已采纳

如果没有返回json对象,php输出在哪里

Sorry, no doubt a really basic question... but I haven't found a possible duplicate.

If at the end of a php script called using $.getJSON() I have a line like this:

return json_encode( $paras_of_interest );

... everything works fine ... until there is some php output (inadvertently by an echo command, or perhaps due to a warning or error being generated by the php code)... this then completely disables/stops/messes up the return of the JSON object. What's the best way of dealing with this situation? How can one find out what code was output (i.e. where does it "go"?) ... and is there a way of configuring where output goes in this situation?

later apologies to Dezigo and Salman A: all 3 were excellent answers but I had to choose one

  • 写回答

3条回答 默认 最新

  • dongpuchao1680 2013-02-26 10:14
    关注
    1. Make sure there will be no output before this line:

      • For errors, set the display_errors directive to 0 and/or use a custom error handler
      • For exceptions, use a try/catch block
      • For other output, if there might be any, use output buffering (ob_start and ob_get_clean)
    2. If you captured any unexpected output/errors, don't send it, but add an error parameter to your JSON response:

      echo json_encode(array(
        'result' => /* your original result here */,
        'error'  => /* error message here */
      );
      

    Your response should always be structured like this, error being null or false if no error occurred. On the client side you will evaluate error first, then result. Additionally you could send a HTTP 500 status code if an error occurred, then you should be able to use the error callback function of JQuery to handle errors:

    $statusCode = $error ? 500 : 200;
    header('content-type: application/json',  true, $statusCode);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题