0

基本上,我想提交一个创建新课程表单并使用 JQuery 处理响应。我的表格喜欢

<div id="create_coursem">
  <%= form_tag({:controller => "coursem", :action => "create"}, :id => "check_coursem_form", :method => "post", :remote => true) do %>
      <p>
      <b> <%= label_tag(:name, "Name:") %> </b>
      <%= text_field_tag(:name) %>
      </p>
      <p>
      <b> <%= label_tag(:department, "Department:") %> </b>
      <%= select_tag "department", @result.html_safe %>
      </p>
      <%= submit_tag("Create") %>

  <% end %>

</div>

在我的控制器中,我有

  def create
    @coursem = Coursem.createCoursemByUser(params[:name], params[:department])
    @errCode = @coursem
    if @coursem.class != Fixnum
      @errCode = 1
    end
    @dic = {:errCode => @errCode, :coursem => @coursem}
    respond_to do |format|
      format.json { render json: @dic}
    end
  end

响应状态为200,表示成功返回了一个json。在我的 JS 文件中,我有

$(document).ready(function() {
    panelHandler();
    //showOverview();
    showResources();
    resourceHandler();
    calendarChangeMonth();
    subscribeHandler();

    shownewresourceform();

    eventinfo();
    closeeventbox();
    showneweventform();
    colorrecentevents();
    check_coursem();
})
    function check_coursem() {
        $("form#check_coursem_form").on('ajax:beforeSend', function(xhr, settings) {alert("hello");})
                                .on('ajax:success',    function(data, status, xhr) {alert("hello");})
                                .on('ajax:complete', function(xhr, status) {alert("hello");})
                                .on('ajax:error', function(xhr, status, error) {alert("hello");});
    }

但是当我单击创建按钮时,它只返回创建控制器生成的 json,不显示任何警报。有谁知道原因吗?非常感谢。

4

2 回答 2

0

也许它会尝试将响应解析为 javascript 响应,而不是 json 响应。

尝试这个:

form_tag({:controller => "coursem", :action => "create"}, :id => "check_coursem_form", :method => "post", :remote => true, :data => { :type => 'json' }) do %>
于 2013-04-24T08:02:46.517 回答
-1

我没有大量使用 ajax,但我从未见过像这样格式化的请求...您是否尝试过在文档中实现类似的东西?

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "example.php" )
    .done(function() { alert("success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() { alert("second complete"); });
于 2013-04-24T03:55:25.563 回答