Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel angularjs请求::ajax()始终为false_Php_Ajax_Angularjs_Coffeescript_Laravel 4 - Fatal编程技术网

Php Laravel angularjs请求::ajax()始终为false

Php Laravel angularjs请求::ajax()始终为false,php,ajax,angularjs,coffeescript,laravel-4,Php,Ajax,Angularjs,Coffeescript,Laravel 4,我正在用angularjs和Laravel4构建应用程序。 一切都很好,但我现在只需要允许XHR请求 这是我在控制器开始时所拥有的。 但这种说法总是错误的 if (!\Request::ajax()) { return Response::json(array('halt'=>Request::ajax())); }; 在angular中,我使用的是标准的$http服务 angular.module('APP') .factory("API", (

我正在用angularjs和Laravel4构建应用程序。 一切都很好,但我现在只需要允许XHR请求

这是我在控制器开始时所拥有的。 但这种说法总是错误的

    if (!\Request::ajax())
    {
        return Response::json(array('halt'=>Request::ajax()));
    };
在angular中,我使用的是标准的$http服务

angular.module('APP')
.factory("API", ($http,$q,appClient,apiURL) ->
 class FB
  constructor:->
    this.deferredData = $q.defer();
  info: (reload)->
    $http(
      method: "get"
      url: apiURL+'game/'+appClient+"/info"
    ).success((res)->
      dostuff()
    )

在进行AJAX调用时,
X-request-With
头通常设置为
XMLHttpRequest
。Laravel的
Request::ajax()
方法构建在一个Symfony2方法之上,该方法只检查是否存在此头

2012年10月,Angular.js使用了这个标题,因为他们觉得它很少被使用

正如@structmaster和您在评论中提到的,您需要设置:

$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"

如果您不想修改前端angular应用程序(或者不能),而是想修改Laravel代码来区分angular JS AJAX请求和其他请求,那么您还可以使用:


wantsJson
方法依赖于标准的
接受
HTTP头(而不是非标准的
X-request-With
头)来显示
application/json
。只要AngularJs在默认情况下将其保留,并且您没有故意删除它,此方法就应该是可靠的。

对于AngularJs新手来说,在哪里添加
$httpProvider.defaults.headers.common[“X-request-With”]=“XMLHttpRequest”

以下是一个例子:

var angularApp = angular
  .module('angularApp', [
    'ngResource',
  ])
  .config(['$httpProvider', function($httpProvider) {
      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
  }]);

。大多数浏览器在进行AJAX调用时通常会设置一个标题:
X-request-With:XMLHTTPRequest
。您看到浏览器检查器中的标题了吗?非常感谢,我必须设置:
$httpProvider.defaults.headers.common[“X-Requested-With”]=“XMLHttpRequest”
是的,我知道这个问题很老了。这个答案只是为了把它从“未回答的问题”列表中去掉——这就是为什么它是社区维基。谢谢,我喜欢这个解决方案:)完美。这正是我想要的。加上我的2美分-这个答案在某些情况下会有帮助,但在其他情况下不会有帮助,例如当angular加载模板文件(路由器、指令等)-虽然技术上是通过ajax完成的,但Laravel
Request::wantsJson()
不会拦截它。Moshe接受的答案是,IMOH是验证所有请求是否得到正确处理的更好方法。无论如何,在Laravel方面,您应该始终检查if(Request::isAjax()| | Request::wantsJson()){}
var angularApp = angular
  .module('angularApp', [
    'ngResource',
  ])
  .config(['$httpProvider', function($httpProvider) {
      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
  }]);