zaj*_*jca 29 php ajax coffeescript angularjs laravel-4
我正在用angularjs和laravel构建应用程序4.一切都很好但我现在只需要允许XHR请求.
这就是我在控制器开头所拥有的.但这种说法总是错误的.
if (!\Request::ajax())
{
return Response::json(array('halt'=>Request::ajax()));
};
Run Code Online (Sandbox Code Playgroud)
在角度我使用标准的$ 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()
)
Run Code Online (Sandbox Code Playgroud)
Mos*_*atz 38
在进行AJAX调用时,X-Requested-With标题通常设置为XMLHttpRequest.Laravel的Request::ajax()方法建立在Symfony2方法之上,该方法只检查此标头的存在.
2012年10月,Angular.js 删除了这个标题,因为他们觉得很少使用它.
正如@Thrustmaster和您在评论中提到的那样,您需要设置:
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"
Run Code Online (Sandbox Code Playgroud)
Jef*_*ert 23
如果您不想修改前端角度应用程序(或不能),而宁愿修改Laravel代码以区分Angular JS AJAX请求与其他请求,您还可以使用Request::wantsJson():
if(Request::wantsJson()) {
// Client wants JSON returned
} else {
// Client does not want JSON returned
}
Run Code Online (Sandbox Code Playgroud)
该wantsJson方法依赖于标准AcceptsHTTP头(而不是非标准X-Requested-With头)的存在application/json.只要Angular JS默认将其保留,并且您没有故意删除它,此方法应该是可靠的.
Eme*_*bah 14
对于AngularJs新手寻找添加的位置 $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"
这是一个例子:
var angularApp = angular
.module('angularApp', [
'ngResource',
])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
Run Code Online (Sandbox Code Playgroud)