gpt4 book ai didi

javascript - 在 Rails Controller 中发回 ajax 错误响应

转载 作者:行者123 更新时间:2023-11-28 08:12:02 26 4
gpt4 key购买 nike

我正在尝试向 Rails Controller 中的 ajax 调用发回错误响应。

下面是我在 Controller 中创建的操作,即带有 ajax 调用的 javascript 函数。我需要发回错误响应,以便调用 ajax 请求的错误部分。我不知道如何让它发挥作用。

  def create
@company = Company.find(params["company_id"])
@campaign = @company.campaigns.build(campaign_params)
if @campaign.save
redirect_to campaign_get_campaigns_path(@company)
else
respond_to do |format|
format.json {render :json => {:error_message => @campaign.errors.full_messages, :success => false } }
end
end
end


$(document).on('click', '#submitCampaign', function (e) {
$form = $('.new_campaign');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
dataType: "json"
});
error: function(data) {
newfunction(data);
}
});

我在终端中得到的响应是:

Completed 200 OK in 269ms (Views: 0.2ms | ActiveRecord: 9.9ms)

最佳答案

您必须定义响应:status。在这种情况下,最好的选择是422 UnprocessableEntity

format.json { render :json => { :error_message => @campaign.errors.full_messages }, :status => :unprocessable_entity }

关于javascript - 在 Rails Controller 中发回 ajax 错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com