Jquery 访问控制允许源getJSON Rails
我有一些代码在开发中运行良好 原始代码Jquery 访问控制允许源getJSON Rails,jquery,ruby-on-rails,json,cors,Jquery,Ruby On Rails,Json,Cors,我有一些代码在开发中运行良好 原始代码 respond_to :json def index @tags = current_user.tags respond_with(@tags.map{|tag| {:id => tag.id, :name => tag.name} }) end def index @tags = current_user.tags respond_to do |format| if params[:callback]
respond_to :json
def index
@tags = current_user.tags
respond_with(@tags.map{|tag| {:id => tag.id, :name => tag.name} })
end
def index
@tags = current_user.tags
respond_to do |format|
if params[:callback]
format.json { render :json => @tags.map{|tag| {:id => tag.id, :name => tag.name} }.to_json , :callback => params[:callback]}
else
format.json { render :json => @tags.map{|tag| {:id => tag.id, :name => tag.name} }}
end
end
end
有一个路由文件
get "tags/index"
我的jQuery文件有这样一行
$.getJSON('http://localhost:3000/tags.json', function(data) {
但是,当将其推到生产时,我得到一个错误
XmlHttpRequest错误:访问控制不允许原点允许原点。在做了一些研究之后
及
我把代码改成了这个
新代码
respond_to :json
def index
@tags = current_user.tags
respond_with(@tags.map{|tag| {:id => tag.id, :name => tag.name} })
end
def index
@tags = current_user.tags
respond_to do |format|
if params[:callback]
format.json { render :json => @tags.map{|tag| {:id => tag.id, :name => tag.name} }.to_json , :callback => params[:callback]}
else
format.json { render :json => @tags.map{|tag| {:id => tag.id, :name => tag.name} }}
end
end
end
及
同样的路线
这是怎么回事?我仍然收到相同的错误,为什么回调没有修复它
所有jQuery代码
var items = [];
var prepopulate = [];
$(function () {
var myVarsJSON = $("#my_vars_json").html(),
myVars = $.parseJSON(myVarsJSON);
$.each(myVars, function(i, obj) {
return prepopulate.push(obj.name);
});
$.getJSON('/tags.json' + '&callback=?', function(data) {
$.each(data, function(i, obj) {
return items.push(obj.name);
});
$("#article_tag_ids_edit").val(prepopulate).select2({
width: "element",
tags: items,
tokenSeparators: [",", " "]
});
});
});
$.getJSON('/tags.json' + '&callback=?', function(data) {
$.each(data, function(i, obj) {
return items.push(obj.name);
});
$("#article_tag_ids").select2({
width: "element",
tags: items,
tokenSeparators: [",", " "]
});
});
试试这个
而不是
$.getJSON('http://localhost:3000/tags.json' + '&callback=?', function(data)
用这个
$.getJSON('/tags.json' + '?callback=?', function(data)
@ebbflowgo如果您正在签入生产环境,请清理并重新编译所有资产。我现在收到一个新错误。获取url.com/tags.json&callback=jQuerysomthing 406(不可接受)Hi Sachin Singh,我已经发布了它above@ebbflowgo在代码中使用“?callback=?”而不是“&callback=?”。Sachin Singh,我得到了相同的get 406错误。但是,当我插入tags.json?callback=?在URL中,我确实得到了json填充,这是一个好迹象。作为旁注,当我这样做时?回调=?JSON前面有一个“?”,所以我认为最好使用?回调=