简体   繁体   English

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

[英]Selecting data from another page in Ajax

This is my ajax handling code: 这是我的ajax处理代码:

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

How to tell Ajax to take the results from the next page in the shirts/first file? 如何告诉Ajax从Shirts /第一个文件的下一页获取结果? I wrote the code as I've shown but it throws a error saying 'syntax error'! 我按照显示的方式编写了代码,但抛出了一个错误,提示“语法错误”! How can I solve this? 我该如何解决?

Also my .js.erb file if its of some help: 还有我的.js.erb文件,如果有帮助的话:

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

If you're performing ajax pagination, you'll have to ensure you can handle the Ajax request on the controller (using respond_to ), and send the correct data: 如果要执行ajax分页,则必须确保可以在控制器上处理Ajax请求(使用respond_to ),并发送正确的数据:

JS JS

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

You'd need to have your pagination buttons with the page's ID for this 为此,您需要使用带有页面ID的分页按钮


Controller 调节器

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

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

View 视图

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

you have mixed the rails params and javascript code, in javascript 您已经在JavaScript中混合了Rails参数和javascript代码

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

has syntax error because of : charachter, and even if you remove it means you have a javascript object named params and page is a variable which refers to a key in the params object, whereas here params[:page] refers to a querystring which its key is page in the current request from the client. 由于: charachter而导致语法错误,即使删除它,也意味着您有一个名为params的javascript对象,而page是一个变量,该变量引用了params对象中的键,而此处params[:page]引用了一个查询字符串,关键是客户端当前请求中的page

So change it like: 因此,将其更改为:

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

You have to be careful here, cause the code above means the current page is being loaded with the page in its querystrings like: http://example.com/homepage?page=helloworld and helloworld probably is the other page in your story. 您在这里必须小心,因为上面的代码意味着当前页面正在以查询字符串的形式加载该page ,例如: http://example.com/homepage?page=helloworld : http://example.com/homepage?page=helloworld page= helloworldhelloworld可能是您故事中的另一个页面。

and for your .js.erb file, in rails 3.0.8, you have to wrap every escape_javascript call with raw() : 对于.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