表单提交错误后显示基于ajax的元素 [英] Show ajax based elements after form submit error

查看:16
本文介绍了表单提交错误后显示基于ajax的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有两个选择元素,类别和子类别.起初,只显示类别选择.当用户在类别选择中进行选择时,会向服务器发送 AJAX 请求并显示子类别选择.它工作正常.

现在,当表单提交中出现一些错误时,由于任何原因,缺少某些必需的值,或任何原因,我会显示错误消息,但我无法保留选择框的相同状态,我只看到类别选择,没有选择值,即初始状态.谁能建议我如何保留这些选择元素的状态?

这是我的新表单的代码片段:

 

类别 <%= collection_select :post_category, :id, @categories, :id, :name,选项 = {:prompt =>选择一个类别"} %>

<div id="sub-category-select">

这是我的 jQuery 脚本,它在类别选择上进行选择时发送 AJAX 请求:

$("#post_category_id").change(function() {var category_id = $('select#post_category_id :selected').val();if(category_id == "") category_id="0";$.get('/posts/update_sub_cat/' + category_id, function(data){$("#sub-category-select").html(data);})返回假;});

AJAX 请求是在 post_controller 中的 update_sub_cat 动作上发出的,如下所示:

def update_sub_cat如果 params[:id].present?@sub_categories = Category.find_all_by_parent_id(params[:id])别的@sub_categories = []结尾response_to do |格式|格式.js结尾

结束

AJAX 请求呈现 update_sub_cat.js.erb 文件,我在其中使用了一些 HMTL

sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name,选项 = {:prompt =>选择一个子类别"} %>

我知道,我不应该在这里直接使用 HTML,而应该使用 $('sub-category-select).append(...),但我是这样工作的,打算以后再改.

这是我程序这部分涉及的所有代码.

有人可以帮我吗?

解决方案

我解决了这个问题,并得到了基于 AJAX 的元素来维护状态.这是我的 jQuery 代码:

$('#before_category_select').loadPage();jQuery.fn.loadPage = 函数(){if($("#new-post-area").length > 0){$.getJSON('/home/cat_select_state.json', function(data){$.get('/posts/update_sub_cat/' + data.cat_state, function(data1){$("#sub-category-select").html(data1);})});}}

我调用的控制器操作以获取选择元素的状态,在页面提交时存储为会话变量:

 def cat_select_state@cat_session = {:cat_state =>session[:new_post_category], :sub_cat_state =>会话[:new_post_sub_category]}response_to do |格式|format.json {render :json =>@cat_session}结尾结尾

最后,我为选择框使用了默认值,这些值存储为会话变量.如果会话变量为空,则默认为选择框的提示信息.

<%= collection_select :post_category, :id, @categories, :id, :name,选项 = {:prompt =>"选择一个类别", :selected =>session[:new_post_category]} %>

子类别选择元素的 HTML 在 javascript 文件 update_sub_cat.js.erb 中呈现.

sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name,选项 = {:prompt =>选择一个子类别"} %>

如果您有更多改进,请提出建议.

I have two select elements in my form, Category and Sub-category. At first, only the category select is shown. When the user makes a selection in the category select, an AJAX request is sent to the server and the subcategory select is shown. It works fine.

Now, when there is some error in the form submit, due to anything, missing some value that is required, or anything, I show the error message, but I cannot retain the same state of the select boxes, I see only the category select, with no value selected, i.e the initial state. Can anyone suggest me how I can preserve the state of these select elements?

Here's a code snippet from my new form:

    <div id="category-select">
    category <%= collection_select :post_category, :id, @categories, :id, :name, 
                                                options = {:prompt => "Select a category"} %>
    </div>
    <div id="sub-category-select">
    </div>

Here's my jQuery script that sends AJAX request when a selection is made on Category select:

$("#post_category_id").change(function() {
  var category_id = $('select#post_category_id :selected').val();
  if(category_id == "") category_id="0";
    $.get('/posts/update_sub_cat/' + category_id, function(data){
       $("#sub-category-select").html(data);
    })
  return false;
});

The AJAX request is made on the update_sub_cat action in the post_controller, which is shown below:

def update_sub_cat
  if params[:id].present?
    @sub_categories = Category.find_all_by_parent_id(params[:id])
  else
    @sub_categories = []
  end
  respond_to do |format|
    format.js
  end

end

The AJAX request renders update_sub_cat.js.erb file, in which I have used some HMTL

sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name, 
                                        options = {:prompt => "Select a sub-category"} %>

I know, I should not directly use HTML here, but rather use $('sub-category-select).append(...), but I got it working like this, and am planning to change it later.

This is all the code that is involved in this part of my program.

Can anyone help me, please?

解决方案

I solved the problem, and got the AJAX based element to maintain state. Here's my jQuery code:

$('#before_category_select').loadPage();

jQuery.fn.loadPage = function(){
if($("#new-post-area").length > 0){
    $.getJSON('/home/cat_select_state.json', function(data){
        $.get('/posts/update_sub_cat/' + data.cat_state, function(data1){
           $("#sub-category-select").html(data1);
        })
    });
   }
}

The controller action that I call to get the state of the select elements, which is stored as session variables at the time of page submit:

  def cat_select_state
    @cat_session = {:cat_state => session[:new_post_category], :sub_cat_state => session[:new_post_sub_category]}
    respond_to do |format|
      format.json {render :json => @cat_session}
    end
  end

And finally, I used a default values for the select boxes, which are stored as session variables. If the session variable is null, the default value is the prompt message for the select box.

<%= collection_select :post_category, :id, @categories, :id, :name, 
                                                options = {:prompt => "Select a category", :selected => session[:new_post_category]} %>

The HTML for sub-category select element is rendered in the javascript file update_sub_cat.js.erb.

sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name, 
                                        options = {:prompt => "Select a sub-category"} %>

Please suggest if you have any more improvements.

这篇关于表单提交错误后显示基于ajax的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆