Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Rails提交Ajax表单_Javascript_Jquery_Ruby On Rails_Ajax - Fatal编程技术网

Javascript 使用Rails提交Ajax表单

Javascript 使用Rails提交Ajax表单,javascript,jquery,ruby-on-rails,ajax,Javascript,Jquery,Ruby On Rails,Ajax,在我的Rails应用程序中,我想在用户上传图像时更新模型。选择图像后,图像立即在页面上呈现,但图像应作为AJAX调用在后台上传。换句话说,表单应提交,用户无需单击提交按钮,一旦选择文件,表单应自动提交 在我当前的实现中,新上传的图像会出现在页面上,但它会触发HTML更新,导致页面刷新,即使表单上的remote设置为true如何确保表单作为AJAX请求提交? (我遵循了本页上的示例:) 你应该使用 $.post('yourURL', this.form.serialize()) 而不是 this

在我的Rails应用程序中,我想在用户上传图像时更新模型。选择图像后,图像立即在页面上呈现,但图像应作为AJAX调用在后台上传。换句话说,表单应提交,用户无需单击提交按钮,一旦选择文件,表单应自动提交

在我当前的实现中,新上传的图像会出现在页面上,但它会触发HTML更新,导致页面刷新,即使表单上的remote设置为true如何确保表单作为AJAX请求提交?

(我遵循了本页上的示例:)

你应该使用

$.post('yourURL', this.form.serialize())
而不是

this.form.submit();

这就是最终对我有效的方法(其中#collection_image是文件_字段的id,#collection_image_form是表单)


参数中不包括图像文件“图像文件”是什么意思?是否要将“src”包含到参数中?用户使用表单的file\u field元素上载图像。这需要作为表单中的一个参数上传,这似乎不是使用您的建议实现的。我根据此页面上的建议更新了我的代码(但仍然不起作用)
  $('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;        
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }
    $('#collection_avatar_form').trigger('submit.rails');
  });
$.post('yourURL', this.form.serialize())
this.form.submit();
$('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;              
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }

    $.ajax({
          type: "POST",
          url: $('#collection_avatar_form').attr('action'), 
          data: new FormData($('#collection_avatar_form')[0]),
          processData: false,
          contentType: false,          
          dataType: "JSON" 
      }).success(function(json){
          console.log("success", json);
    });

  });