Ruby-on-rails 简单地从 rails 中的 ajax 调用返回成功或失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3792685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:15:41  来源:igfitidea点击:

Simply returning success or failure from ajax call in rails

ruby-on-railsajaxjson

提问by 99miles

I have a little ajax call that calls rails:

我有一个调用 rails 的 ajax 调用:

    $.ajax({
        type: "POST",
        url: '...',
        data: ({    ...
                }),
        success:    function(response, status) {
                    console.log(status);
        }
     });

In the rails controller I'm simply deleting an entry from the database, and I simply want to return if it was successful or not. What's the best way?

在 rails 控制器中,我只是从数据库中删除一个条目,如果成功与否,我只想返回。最好的方法是什么?

Should I just return JSON in respond_to? If so, what exactly would you have it contain?

我应该在 response_to 中返回 JSON 吗?如果是这样,你究竟希望它包含什么?

回答by Dave Pirotte

Best way to signify success in this way is to put the following in your controller...

以这种方式表示成功的最佳方式是将以下内容放入您的控制器中...

def destroy
  # ... your code ...
  respond_to do |format|
    format.json { head :ok }
  end
end

回答by El Fadel Anas

try this it's working for me

试试这个它对我有用

def destroy 
  ...        
  render json: {}, status: 200
end

回答by Eugene

I found this shorter way to do the job:

我发现这种更短的方式来完成这项工作:

def destroy
  # ... your code ...
  head :ok # this will return HTTP 200 OK to jQuery!
end

回答by sushil bharwani

When you execute your query it might be returning some code that says it executed succesfully to confirm that row was deleted. So you can return that just to make sure query was also executed successfully along with the ajax call.

当您执行查询时,它可能会返回一些代码,表明它已成功执行以确认该行已被删除。所以你可以返回它只是为了确保查询也与 ajax 调用一起成功执行。