0

我遇到了这个 Laravel 4 问题,这让我很困惑。我在同一个控制器上创建了这两种方法。控制器声明为安静。ajax 请求来自不同的域。

不工作

public function getOwnlist(){
    $test = User::with(array("images", "images.category"))->find(Auth::user()->id);
    return Response::json($test, 200, array('Access-Control-Allow-Origin' => '*'));
}

作品

public function getLatest(){
        $images = DB::table("images")->where("public","=","1")->orderBy("created_at")->take(10)->get();
        return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*'));
}

浏览器得到一个标准的跨域错误。

4

1 回答 1

3

这个例子对我有用,你可以试试这个。

public function getOwnlist(){
   $images = User::with('images.category')->find(Auth::getUser()->getAttribute('id'));
   return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*'));
}

此外,我强烈建议在 Controller Base 的构造函数中设置这些,而不是在每个响应中设置标头。或者您可以创建一个仅用于提供 API 并从中扩展的。

应该是这样的:

protected $response; // This is a global variable on you BaseController

// This goes on your BaseController constructor 
$this->response = Response::make();
$this->response->headers->add(array('Access-Control-Allow-Origin', '*');

我在使用 jQuery 时发现了跨域 AJAX 的一些问题,如果我指定域而不是使用*.

有关 Eloquent 模型的更多信息:http: //laravel.com/docs/eloquent#querying-relations

于 2013-09-30T15:10:10.117 回答