返回数组对象时出错


Error when returning array object

我在返回数组对象并将其显示给用户时遇到问题,请查看演示代码。一个基本的片段,但它有相同的想法,我只是不能在这里发布很长的代码。

Class foobar{
   public function foo()
   {
     return array( 'bar' => 'value' );
   }
}

这个php代码被另一个类使用

Class foobar_fetcher{
   public function getFoo()
   {
     $fb = new foobar();
     $result = $fb->foo();
     return $result;
   }
}

foobar_fetcher再次由主执行器文件(ajaxdispatcher.php)调用,该文件带有json头。

if( isset( $_POST['fetch'] ) ){
   $httpresponse = new stdClass();
   $fb_fetch = new foobar_fetcher();
   $httpresponse->data = $fb_fetch->getFoo();
}
echo json_encode( $httpresponse );

最后,这个ajaxdispatcher被一个jquery ajax调用。

$.ajax({
  url: 'ajaxdispatcher.php',
  type: 'post',
  data: {fetch:'fetch'},
  success: function( data ){
      if( data ) console.log( data );
  }
});

现在,当我尝试打印出数据时,它没有来自服务器的响应。但是当我将foobar类下的foo()的返回值更改为整数或字符串时。一切都会好起来的。

您应该尝试更改ajaxdispatcher以接受GET请求,并从浏览器导航到那里查看返回的内容。

if( isset( $_GET['fetch'] ) ){
   $httpresponse = new stdClass();
   $fb_fetch = new foobar_fetcher();
   $httpresponse->data = $fb_fetch->getFoo();
}
echo json_encode( $httpresponse );

导航到/ajaxdispatcher.php?fetch=提取

我想做的一些事情可能会提高你成功的机会

  1. 在发送JSON代码后立即设置适当的HTTP标头和exit

    header('Content-type: application/json');
    echo json_encode($httpresponse);
    exit;
    

    还要确保在此之前没有向输出缓冲区发送任何数据。

  2. 告诉jQuery期望的数据类型

    $.ajax({
        dataType: 'json',
        // and the rest
    
  3. 添加error回调

    $.ajax({
        // snip
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        }
    });