繁体   English   中英

从Ajax中的另一个页面选择数据

[英]Selecting data from another page in Ajax

这是我的ajax处理代码:

$.ajax({
    url: "shirts/first?page=" + params[:page],
    type: "GET"
})

如何告诉Ajax从Shirts /第一个文件的下一页获取结果? 我按照显示的方式编写了代码,但抛出了一个错误,提示“语法错误”! 我该如何解决?

还有我的.js.erb文件,如果有帮助的话:

$("#container1").append("<%= escape_javascript(render 'shirts/first')%>");

如果要执行ajax分页,则必须确保可以在控制器上处理Ajax请求(使用respond_to ),并发送正确的数据:

JS

#app/assets/javascripts/application.js
$("a.pages").on("click", function() {
    $.ajax({
        url: "shirts/first?page=" + $(this).attr("id"),
        type: "GET"
    });
});

为此,您需要使用带有页面ID的分页按钮


调节器

#app/controllers/shirts_controller.rb
def first
    @shirts = Shirt.where(your_query)

    respond_to do |format|
        format.html
        format.js
    end 
end

视图

#app/views/shirts/first.js.erb
$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");

您已经在JavaScript中混合了Rails参数和javascript代码

url: "shirts/first?page=" + params[:page]

由于: charachter而导致语法错误,即使删除它,也意味着您有一个名为params的javascript对象,而page是一个变量,该变量引用了params对象中的键,而此处params[:page]引用了一个查询字符串,关键是客户端当前请求中的page

因此,将其更改为:

$.ajax({
    url: "shirts/first?page=<%= params[:page] %>",
    type: "GET"
});

您在这里必须小心,因为上面的代码意味着当前页面正在以查询字符串的形式加载该page ,例如: http://example.com/homepage?page=helloworld : http://example.com/homepage?page=helloworld page= helloworldhelloworld可能是您故事中的另一个页面。

对于.js.erb文件,在rails 3.0.8中,您必须使用raw()包装每个escape_javascript调用:

$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM