0

我有这个作为我的查看页面

<html>
    <head>
        <script>
            function submit_form() 
            {
                    $('#my_form').submit();
            }
        </script>
    </head>
    <body>
        <div class="container">

            <%= form_tag({:action => 'submit_form'}, :remote => true,:method=>:post,:id => 'my_form',:class => 'my_form_class') do %>
                <%= select(:grade,:id,@distinct_grade_list,{},:onchange => "submit_form()")%>
                <%= select(:period,:id,@distinct_period_list)%>
            <% end %>
            <br/>
            <div id="farzi2" style="border: 3px solid blue;margin-top: 20px">
                <%= select(:student_name,:id,{},{},{ :multiple => true, :size => 4 }) %>
            </div>
    </body>
</html>

现在,当我更改第一个选择框的内容时,javascript 函数通过 ajax 提交表单并发送回表单中提到的控制器操作

在我的控制器动作中

def submit_form
    puts "in submit_form action"
    @hussi = "submit_form"
    @student_name_list = Student.pluck(:student_name)


    respond_to do |format|
      format.html { redirect_to 'roles' }
      format.json { head :no_content }
      format.js   { render :json => @student_name_list }
    end
  end

现在我的问题是,我如何在相关 js 中使用这些 @hussi 和 @student_name_list 数据。erb文件设置查看页面显示的内容

我的 submit_form.js.erb 文件到目前为止什么都没有

alert("in submit_form js");
$('.my_form_class').on('ajax:success', function()
{
alert(<%=@student_name_list%>")
})

我想要的只是使用从名为 action(submit_form) 的 ajax 传递的这个列表 (@student_name_list) 在 ajax 请求成功返回后用于我的视图页面中的选择选项框。

4

3 回答 3

2

我知道 Abhi 不久前就回答了这个问题,但我发现他们写的东西很有用(我赞成“谢谢”。代码中有一些错误,所以我想我会更新一个版本工作(就像在我的项目中一样)。希望这对将来的某人有所帮助:

$('.my_form_class').on('submit', function() {
    $.ajax({
        type: "POST",
        url: "/",
        data: "your_data",
        dataType: "html",
        success: function(data) {
            // response is like : [{text:"A",value:1},{text:"B",value:2}]
            var option="";
            $.each(data,function(index,value) {
                option += "<option value='"+index+"'>"+value+"</option>";
            });
            $("#your_html_placeholderid").html(option);
        }
   });
});
于 2013-11-08T16:09:59.810 回答
1

假设您正在获取 json 格式的数据:

$('.my_form_class').on('submit', function()
{
     $.ajax({
    type: "POST",
    url: "/",
    data: "your_data",
    dataType: "html",
       success: function(data) {
              // response is like :   [{text:"A",value:1},{text:"B",value:2}]
             var opt="";
             $.each(data,function(ind,val){
                 option+="<option value='"+val.value+"'>"+val.text+"</option>"
             });
      $("#your_html_placeholderid").html(data);
    }

});

});

当您在成功回调中获取数据时,您必须知道需要更改哪个 select/html 元素。所以通过 $("#yourid").html("your result format") 将有助于用您分配的数据刷新元素。

于 2013-06-27T07:46:29.317 回答
0

从 format.js 中删除render :json => @student_name_list,看看你是什么。

@student_name_list 在您的 js 文件中自动可用。

于 2013-06-28T15:12:26.540 回答