How do I write my create action in a controller to accept data from another server?
Is this possible with JSONP? What about same origin policy?
I only need to worry about HTML5 compliant browsers. Thanks!
$.ajax({
type: 'POST',
url: 'http://pinky.local:3000/items',
dataType: 'jsonp',
success: function(data) {
console.log(data)
},
processData: false,
data: "{\"item\":{\"name\":\"foobar\"}开发者_如何转开发}"
})
Controller
def create
@item = Item.new(params[:item])
end
ERROR: XMLHttpRequest cannot load http://pinky.local:3000/items. Origin http://foo.local is not allowed by Access-Control-Allow-Origin.
$(function() {
$('a').click(function(e){
$.ajax({
data: "{\"item\":{\"name\":\"foobar\"}}",
type:'POST',
url:'http://localhost:3000/items/upload',
success: function(response) {
alert('Successfully sent data!');
},
error: function(event, jqXHR, ajaxSettings, thrownError) {
}
});
});
});
</script>
match '/items/upload' => "items#upload", :conditions => { :method => :options }
def upload
#Needs these headers for the cross-domain ajax
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'x-requested-with'
if request.post?
@item = Item.new(params[:item])
@item.pic = data
@item.save!
end
render :text => 'success'
end
精彩评论