【问题标题】:Ajax request to Laravel 4 returns 200 ok but method always return fail对 Laravel 4 的 Ajax 请求返回 200 ok 但方法总是返回失败
【发布时间】:2013-11-15 06:21:02
【问题描述】:

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 响应默认不发送

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

刚刚添加,现在我可以正确获取 json 数据。

【问题讨论】:

  • 主机名是不同的主机名吗?这可能是 CORS 安全类型问题。
  • 您的 JSON 输出无效。这就是为什么即使状态为 200 OK,方法也会失败的原因。
  • 嗨,JSON 输出似乎有效(在 JSONlint 上测试),我无法捕捉到使用 chrome 或 firefox 调试的任何错误代码。我在 localhost 上做所有的事情。
  • 我得到的唯一错误是调用url后触发了error函数。
  • 浏览器中有效的 URL 是什么?巧合的是,在 URL 中没有 index.php 的情况下,还是您将 mod_rewrite 首选项设置为那样工作?

标签: jquery laravel laravel-4


【解决方案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;
});

【讨论】:

    猜你喜欢
    • 2014-05-17
    • 2015-08-10
    • 2022-10-04
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2019-03-03
    • 2015-05-12
    相关资源
    最近更新 更多