简体   繁体   中英

Selecting data from another page in Ajax

This is my ajax handling code:

$.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? 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:

$("#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:

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


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

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.

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.

and for your .js.erb file, in rails 3.0.8, you have to wrap every escape_javascript call with raw() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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