简体   繁体   English

Laravel 5.2没有将跨域jQuery方法识别为AJAX

[英]Laravel 5.2 not recognizing cross-domain jQuery method as AJAX

Laravel 5.2 is not recognizing request as AJAX from cross-domain jQuery load() method: Laravel 5.2没有从跨域jQuery load()方法中将请求识别为AJAX:

jQuery from site one: 来自网站1的jQuery:

 $('#results').load('http://site2.com/test');

Controller method on site two: 第二站的控制器方法:

 public function myMethod(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Credentials: true');

        if (!$request->ajax()) {
            abort(403, 'Invalid Request');
        }
          // do something
    }

The request is received and has no issues other than not being recognized as an AJAX request. 收到请求,除了没有被识别为AJAX请求之外没有任何问题。 The load() method called from the same domain IS recognized as AJAX. 从同一域调用的load()方法被识别为AJAX。

Any ideas? 有任何想法吗?

Laravel's HTTP Request class extends Symfony's, which checks the request's X-Requested-With header is set to 'XMLHttpRequest'. Laravel的HTTP Request类扩展了Symfony,它检查请求的X-Requested-With标头是否设置为'XMLHttpRequest'。 This header isn't sent in cross-domain requests with jQuery by default, unless you disable its cross-domain protection: 除非您禁用其跨域保护,否则默认情况下不会在使用jQuery的跨域请求中发送此标头:

$.ajax({
    url: 'http://example.com/',
    crossDomain: false
});

Create a CORS middleware file that includes "X-Requested-With" as an allowed header: 创建一个CORS中间件文件,其中包含“X-Requested-With”作为允许的标头:

public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');

        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
        ];

        if ($request->getMethod() == "OPTIONS") {
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

Replace the jQuery load() method with ajax() and add an 'X-Requested-With' header to the jQuery AJAX call: 用ajax()替换jQuery load()方法,并在jQuery AJAX调用中添加一个'X-Requested-With'标头:

$.ajax({
     type: 'GET',
     url: 'http://site2.com/test',
     headers: {'X-Requested-With': 'XMLHttpRequest'},
     success: function (data)
        {
           //do something
        }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM