对Laravel 4的Ajax请求返回200 ok,但方法总是返回失败

时间:2013-11-04 15:22:37

标签: jquery laravel laravel-4

IM向Laravel网络服务提出简单请求。

这是控制器中的响应:

data = array(
 'name' => 'Dummy',
 'size' => 'XL',
 'color' => 'Blue'
 );
 return Response::json($data);

使用POSTman我可以看到一切看起来很好: 网址:

Response:
{"name":"Dummy","size":"XL","color":"Blue"}

HEADERS:
Cache-Control →no-cache
Connection →Keep-Alive
Content-Type →application/json
Date →Mon, 04 Nov 2013 15:15:27 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.6 (Ubuntu) PHP/5.5.3-1ubuntu2
Transfer-Encoding →chunked
X-Powered-By →PHP/5.5.3-1ubuntu2

然后我进入一个简单的javascript调用,如:

$.getJSON("http://localhost/myapi/public/content", function(json) {
                console.log("log " + json.name);            
            });

$.ajax({ 
type: 'get', 
url: 'http://localhost/myapi/public/content',
 dataType: 'json', 
async: false, 
success: function(data) { alert("success"); }, 
error: function() { alert("error"); } });

Firefox控制台返回“200 OK”,但Javascript始终报告错误。

问题在哪里?

解决方案:

Laravel Response默认情况下不发送

header('Access-Control-Allow-Origin: *');

刚刚添加,现在我正确地获取了json数据。

1 个答案:

答案 0 :(得分:1)

另一种解决方案是在app / filters.php中添加App::after中间件

App::after(function($request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', '*');

    // You may also require these additional method calls
    $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    $response->headers->set('Access-Control-Max-Age', '1000');
    $response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept');

    return $response;
});
相关问题