铁轨 + ajaxForm:使用“错误”;上传文件出错时的回调

发布于 2024-10-19 19:41:05 字数 1466 浏览 5 评论 0原文

背景

我首先想通过 json 上传文件并以这种方式获得响应。

我正在使用:

我很快发现您无法获得 json 格式的响应。因此,我遵循该建议并以文本形式返回。

删除预标记后我就能让事情正常工作。丑陋的解决方案,但这是一个丑陋的问题。

问题

现在,我的问题是处理错误

JS 如下:

$('form#new_image').submit(function() {
  $(this).ajaxSubmit({
    dataType: 'text',
    beforeSubmit: showLoading,
    success: imageUploadSuccess,
    error: imageUploadError
  });
  return false;
});

function imageUploadSuccess(data) {
  var jsonObject = $.parseJSON((/<pre>(.+)<\/pre>/.exec(data))[1]);
  //Do something
}

function imageUploadError(data) {
  alert("FAIL!");
}

即使我响应错误,成功回调(imageUploadSuccess)始终会执行。

这是我的控制器:

def create
  @image = Image.new params[:file]
  @image.imageable_type = params[:imageable_type]
  @image.imageable_id = params[:imageable_id]

  respond_to do |f|
    if @image.save
      logger.debug "PASSED"
      f.text {render :text => @image.to_json}
    else
      logger.debug "FAIL"
      f.text { render :text => "Fail!", :status => 500 }
    end
  end
end

现在,虽然我可以在失败时返回一个包含 success: false 的 json 对象,但总是执行 success 回调感觉很脏。

如何使用错误回调?

Background

I first wanted to upload a file via json and get a response in that way as well.

I'm using:

I soon found out that you can't get a reponse in json. So, I follow that advice and returned as text.

I'm able to get things working after removing the pre tags. Ugly solution, but it's an ugly problem.

Problem

Now, my problem is handling errors.

Here's the JS:

$('form#new_image').submit(function() {
  $(this).ajaxSubmit({
    dataType: 'text',
    beforeSubmit: showLoading,
    success: imageUploadSuccess,
    error: imageUploadError
  });
  return false;
});

function imageUploadSuccess(data) {
  var jsonObject = $.parseJSON((/<pre>(.+)<\/pre>/.exec(data))[1]);
  //Do something
}

function imageUploadError(data) {
  alert("FAIL!");
}

Even if I respond with an error, the success callback (imageUploadSuccess) is always executed.

Here's my controller:

def create
  @image = Image.new params[:file]
  @image.imageable_type = params[:imageable_type]
  @image.imageable_id = params[:imageable_id]

  respond_to do |f|
    if @image.save
      logger.debug "PASSED"
      f.text {render :text => @image.to_json}
    else
      logger.debug "FAIL"
      f.text { render :text => "Fail!", :status => 500 }
    end
  end
end

Now, while I could return a json object with success: false in it when it fails, it just feels dirty that the success callback is always executed.

How do I make use of the error callback?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我很坚强 2024-10-26 19:41:05

以下是一些用于进行 ajax 提交的通用 jQuery 代码:

$('#btn-submit').click(function(event){
    event.preventDefault();
    $.ajax({
        type: "POST",
      url: $('form').attr('action'),
      data:  $('form').serialize(),
      success: function(data) {},
      error: function(data) {}
    });
});

编辑:

我刚刚看到您愿意使用 ajax 上传文件。 Ajax 不允许这种处理,但有很好的替代方案。

我在这里给出两个例子(两个分支): https://github.com /apneadiving/Pic-upload---Crop-in-Ajax

  • with uploadify 使用 flash
  • 和 jQuery Uploader,100% js(使用框架)

Here is some generic jQuery code to make your ajax submission:

$('#btn-submit').click(function(event){
    event.preventDefault();
    $.ajax({
        type: "POST",
      url: $('form').attr('action'),
      data:  $('form').serialize(),
      success: function(data) {},
      error: function(data) {}
    });
});

EDIT:

I just saw you're willing to upload file with ajax. Ajax doesn't allow this kind of processing, but there are great alternatives.

I give two examples here (two branches): https://github.com/apneadiving/Pic-upload---Crop-in-Ajax

  • with uploadify using flash
  • with jQuery Uploader, 100% js (using frames)
勿忘心安 2024-10-26 19:41:05

看来不管你用.ajax还是.ajaxForm提交,只要服务器有响应,success回调就会被执行。

因此,我必须根据情况使用特殊结构的 json 进行回复,该 json 具有 success: true/false 。它最好用控制器操作来说明(我在这里使用inherited_resources,但你明白了):

def create
  create! do |success, failure|
   success.html {redirect_to to}
   success.text do
     image = {
       :id => @image.id,
       :file_name => @image.file_name,
       :success => true
     }
     render :text => image.to_json
   end
   failure.text do
     image = {
      :success => false,
      :errors => @image.errors
     }
     render :text => image.to_json
   end
   success.js
  end
end

It seems that whether you use .ajax or .ajaxForm to submit it, as long as the server responds, the success callback will be executed.

So, I have to reply with specially structured json that has a success: true/false depending on the situation. It's best illustrated with the controller action (I'm using inherited_resources here, but you get the idea):

def create
  create! do |success, failure|
   success.html {redirect_to to}
   success.text do
     image = {
       :id => @image.id,
       :file_name => @image.file_name,
       :success => true
     }
     render :text => image.to_json
   end
   failure.text do
     image = {
      :success => false,
      :errors => @image.errors
     }
     render :text => image.to_json
   end
   success.js
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文