问题
I got this Laravel 4 problem that is really confusing to me. I Created these two methods on the same controller. The controller in declared to be restful. The ajax request is from a different domain.
Does not work
public function getOwnlist(){
$test = User::with(array("images", "images.category"))->find(Auth::user()->id);
return Response::json($test, 200, array('Access-Control-Allow-Origin' => '*'));
}
Works
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' => '*'));
}
The browser get a the standard cross domain error.
回答1:
This example works for me you may try this.
public function getOwnlist(){
$images = User::with('images.category')->find(Auth::getUser()->getAttribute('id'));
return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*'));
}
Also, I highly recommend setting those on the constructor of your Controller Base instead of setting the headers in each response. Or you can create one only to serve API and extend from it.
Should be something like:
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', '*');
I found some issues with Cross Domain AJAX while using jQuery, it only works for me if I specify the domain instead of using *
.
More information on Eloquent Models: http://laravel.com/docs/eloquent#querying-relations
来源:https://stackoverflow.com/questions/18764309/laravel-responsejson-gives-cross-domain-error-i-browser-even-if-header-is-acce