2013-09-24 61 views
0
頁面

在控制器到AJAX請求的響應以下:導軌AJAX(JSON)響應重新加載

@response = {resp: "ack"} 
render json: @response 

JS,其處理AJAX是:

$('#some_btn').click(function() {  

    var valuesToSubmit = $('#some_form').serialize(); 
    var url = $('#some_form').attr('action'); 

    console.log("VALUE: " + valuesToSubmit); 
    console.log("URL: " + search_url); 

    $.ajax({ 
     type: 'POST', 
     url: url, //sumbits it to the given url of the form 
     data: valuesToSubmit, 
     dataType: "JSON", 
     success: function(data) { 

      console.log("saved"); 
      console.log(data); 

     } 
    }); 

    return false; 
}); 

但問題是,我不要獲取控制檯消息,而是重新加載頁面,並在新頁面上獲取json作爲文本。如何防止這種「非真正的AJAX」行爲?

+0

嘗試使用dataType:「json」而不是「JSON」 – techvineet

+0

您確實觸發了ajax請求嗎? – apneadiving

+0

在$ .ajax調用之前,您是否至少獲得了前兩個控制檯消息?根據您的rails日誌,它是否會轉向您期望的控制器和操作?你是否使用類似Firebug的方式檢查了請求和響應的標題,並將它們與工作的AJAX請求中使用的標題進行了比較? – sockmonk

回答

0

您是否需要防止默認表單提交操作?

$('#some_btn').click(function(event) { 
    event.preventDefault(); 

    //... 
}); 
0

我自己也有這個問題。原來,我只是忘了添加「// = require jquery_ujs」到我的application.js文件中。只要我添加它,一切正常。

1

所以,我有幾乎相同的問題。就我而言,我用的是folliwing鏈接發送請求:

<td> 
    <%= link_to add_item_path(item), 
    class: 'ui icon button', 
    id: "add-item-#{item.id}", 
    method: :post do %> 
     <%= fa_icon 'shopping-cart' %> 
    <% end %> 
</td> 

我的JS送AJAX是:

$(document).ready(function() { 
    $("a:regex(id,add-item-[0-9]+)").click(function(event) { 
     event.preventDefault(); 
     var link = $(this).attr("href"); 

     $.ajax({ 
     url: link, 
     method: "POST", 
     dataType: "json", 
     success: function(data) { 
      console.log(data); 
      $('#notice-modal').modal('show'); 
     } 
     }); 
    }) 
    }); 

和我的軌道控制措施是:

def add 
    @item = Item.find(params[:item_id]) 
    current_cart << { item_id: @item.id, quantity: 1 } 
    render json: {quantity: 1} 
    end 

所以問題是我只使用event.preventDefault()但還不夠。爲了工作正常,我需要使用event.stopPropagation()。就像這樣:

$("a:regex(id,add-item-[0-9]+)").click(function(event) { 
    event.preventDefault(); 
    event.stopPropagation(); 
    var link = $(this).attr("href"); 

    $.ajax({ 
     url: link, 
     method: "GET", 
     dataType: "json", 
     success: function(data) { 
     console.log(data); 
     $('#notice-modal').modal('show'); 
     } 
    }); 
    }) 

是需要的,因爲event.stopPropagation()導軌組件(軌道-UJS我認爲)發送請求的其他地方。您也可以刪除method: :post,並且工作正常。

希望我幫了忙!