Jquery 用bookmarklet实现跨域post
基本上,我有一个应用程序来创建与之相关的项目列表。我正在尝试使我的应用程序能够接受带有书签的跨域帖子,以便从我访问的任何网站创建项目。我对rails和jQuery都是新手,因此非常感谢您的帮助 现在,当我第一次按下书签时,我收到一个200 OK的回复。第二次,我收到一个304错误。但是,不会创建任何项 项目\u controller.rbJquery 用bookmarklet实现跨域post,jquery,ruby-on-rails,Jquery,Ruby On Rails,基本上,我有一个应用程序来创建与之相关的项目列表。我正在尝试使我的应用程序能够接受带有书签的跨域帖子,以便从我访问的任何网站创建项目。我对rails和jQuery都是新手,因此非常感谢您的帮助 现在,当我第一次按下书签时,我收到一个200 OK的回复。第二次,我收到一个304错误。但是,不会创建任何项 项目\u controller.rb def create @list = current_user.lists.find(params[:list_id]) @item = It
def create
@list = current_user.lists.find(params[:list_id])
@item = Item.create!(params[:item])
@item.wishes.build(list_id: @list.id)
if @item.save
flash[:success] = "Item created!"
redirect_to @item
else
render 'new'
end
end
bookmarklet.js
alert('Loaded');
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>');
(function($)
{
alert( $('title').text() );
var dataObj = {
'remote_image_url': "http://developer.android.com/assets/images/dac_logo.png",
'title': $('title').text(),
'link': "http://omfg.dk",
'list_id': 5,
'commit': "Add wish"
};
$.ajaxSetup({
type: "POST",
// contentType: "application/json; charset=utf-8",
xhrFields: {
withCredentials: true
},
crossDomain: true
});
$.post('http://localhost:3000/items', dataObj, function(data)
{
//alert('ADDED!!!');
});
}(jQuery));
此外,我还安装了rack/cors gem,设置如下:
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :put, :delete]
end
end
304不是一个错误,它表示资源是缓存的,而不是修改的。有几种方法可以解决此问题: 将web服务器实现修改为不缓存并始终返回200。 将随机字符串附加到url的末尾,以便不缓存它。下面是一个例子:
谢谢-伟大的洞察力!你知道为什么没有创建项目吗?没有创建项目是因为请求没有发送到你的后端。304基本上是指示浏览器使用其缓存响应值而不是在服务器端执行请求的短路。
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :put, :delete]
end
end