2013-09-24 130 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,并且工作正常。

希望我帮了忙!