2013-04-24 54 views
0

基本上,我想提交一個創建新的課程表單並使用JQuery處理響應。 像ajax:succuess在遠程提交表單時未調用rails3

<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,不顯示任何警報。任何人都知道原因? 真的很感謝。

回答

-1

我還沒有與ajax工作過,但我從來沒有見過像這樣格式化的請求... 你有沒有嘗試過更多的東西在documentation

// 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"); }); 
0

也許它試圖解析響應作爲一個JavaScript響應,而不是一個JSON響應。

試試這個:

form_tag({:controller => "coursem", :action => "create"}, :id => "check_coursem_form", :method => "post", :remote => true, :data => { :type => 'json' }) do %>