Hom*_*man 2 json ruby-on-rails xmlhttprequest angularjs
我在Rails应用程序上使用angularjs。我想制作一个分页服务器端数据的搜索表单。
这是我的表格:
<input type="text" class="search-query" placeholder="Search Products" ng-model="search_terms" />
我的rails控制器接受json或html请求:
def index
# ....
respond_to do |format|
format.json {
# ...
}
format.html {
# ...
}
end
end
Run Code Online (Sandbox Code Playgroud)
这是我的角度控制器。由于某种原因,$ http服务只能获取Rails默认的html响应,而无法获取json响应。
$scope.$watch('search_terms',function(newValue,oldValue){
var query = newValue;
$http.get('/products',{params:{search_terms:query}, responseType:'json'}).success(function(data) {
// do something
});
});
Run Code Online (Sandbox Code Playgroud)
如果我使用此jQuery.get,我确实会获取所需的json响应,那么为什么angular会给我html?
jQuery.get('/products',{search_terms:query},function(data){
console.log(data);
}, 'json')
Run Code Online (Sandbox Code Playgroud)
我检查了网络标头,Angular调用与jQuery调用之间的主要区别在于,Angular不会将X-Requested-With标头设置为'XMLHttpRequest'吗?
如果我添加它,那么我可以使其正常工作。
$http.get('/products',{params:{search_terms:query}, responseType:'json', 'headers':{'X-Requested-With':'XMLHttpRequest'}}).success(function(data) {
// do something
});
Run Code Online (Sandbox Code Playgroud)
但是对Angular陌生,我不知道这是否是解决此问题的正确方法。每次都必须这样做,感觉有些笨拙。有没有更好的方法,或者这是使用Angular和Rails时的方法?
我遇到了同样的事情,对此感到沮丧。我的第一个解决方案是解决问题,最后选择了这个宝石:
https://github.com/FineLinePrototyping/angularjs-rails-resource
但是,在有了一些经验之后,我发现它与角度设置不正确的标题有关。
angular.module('yourmodule').run(['$http', function($http) {
$http.defaults.headers.common['Accept'] = 'application/json';
$http.defaults.headers.common['Content-Type'] = 'application/json';
}]);
Run Code Online (Sandbox Code Playgroud)
参考:http : //angulartutorial.blogspot.com/2014/05/set-headers-for-all-http-calls-in.html
请记住,request.xhr的情况也存在
https://github.com/rails/rails/issues/16444
| 归档时间: |
|
| 查看次数: |
1867 次 |
| 最近记录: |