【问题标题】:Error when returning array object返回数组对象时出错
【发布时间】:2012-08-23 05:11:48
【问题描述】:

我在返回一个数组对象然后显示给用户时出现问题,请看演示代码。一个基本的sn-p,但它有相同的想法,我只是不能在这里发布很长的代码。

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() 的返回值更改为整数或字符串时。一切都会好起来的。

【问题讨论】:

标签: php ajax arrays


【解决方案1】:

您应该尝试更改您的 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=fetch

【讨论】:

  • 这个方法我已经试过了。它工作正常。但是当它显示给ajax时,它没有响应。
  • 你用的是什么浏览器?如果您使用的是 Chrome,您可以检查请求和响应,看看哪里出了问题。
【解决方案2】:

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

  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);
        }
    });
    

【讨论】:

  • @KennethPalaganas 那么问题出在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 2023-03-28
  • 2019-02-20
  • 2016-06-16
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多