简体   繁体   中英

how to handle FormData via Ajax on rails server

I am implementing uploading an image using Ajax in my rails 3 app. However, I am stuck on how to handle FormData in my controller. My javascript code looks like this:

var fileData = new FormData($('#photo_form')[0]);
$.ajax({
    type: "POST",
    url: "/photos",
    contentType: false,
    cache: false,
    processData: false,
    dataType: 'json',
    data: fileData,
    success: function() {
        alert("Photo Saved");
    },
    error: function(){
    alert("Error post");
}
});

Then in my controller, I tried to print out params but the formdata doesn't seem to appear. Could anyone give any hint how to handle this? Thanks so much!

In Rails its better to use the Ajax through Rails only, that's easier and good practice, don't write your own calls until its necessary. you can use :remote => true in the form_for while writing the form and data will be available in the controller's action in the params only and you will not have to write this jQuery code by your own.

one more thing remember that when using ajax we cannot have the image data in the controller for that you will have to use remotipart gem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM