How should I update the pagination links in an AJAX call?
So I've implemented AJAX pagination. The problem is that since the <%= paginate @videos %>
code is not inside the partial that I render, the pagination links are not updated. What jQuery code should I use to update the pagination links?
Btw I tried $(".pagination").replaceWith('escape_javascript(<%= paginate @videos %>)');;
but i get this error: Uncaught SyntaxError: Unexpected token ILLEGAL
$(".pagination").replaceWith("escape_javascript(<%= paginate @videos %>)");;
throws this error: Uncaught SyntaxError: Unexpected identifier
Here is the JS code the browser sees:
$(".pagination").replaceWith(" <nav class="pagination">
<span class="prev">
<a href="/profiles/45?_=1302313302990" class="prev" rel="prev">« Prev</a>
</span>
<span class="page first">
<a href="/profiles/45?_=1302313302990">1</a>
</span>
<span class="page current">2</span>
<span class="page last">
<a href="/profiles/45?_=1302313302990&page=3">3</a>
</span>
<span class="next">
<a href="/profiles/45?_=1302313302990&page=3" class="next" rel="next"&开发者_如何学运维gt;Next »</a>
</span>
</nav>
");
Ideally, the new pagination links should be included in the HTML response of the ajax call. If that is not possible - presumably because the links reside elsewhere in the document, then I would suggest creating a context/link/URI/action/whatever (disclaimer: I'm not a ROR guy) which returns a JSON string, structured something like:
[{"data": "The HTML output"}, {"pageLinks": "pagination HTML"}]
and replace your ajax call with one which expects JSON as the return dataType
. Then it should be easy, e.g.:
$.ajax({
url: 'theURL',
dataType: 'json',
success: function(json) {
$('.pagination').html(json.pageLinks);
$('#someDiv').html(json.data);
}
});
The problem looks to be the quotes in your use of replaceWith. You need to escape the characters of that string before trying to use it.
You have double quotes starting and ending your string argument in the replaceWith function but the string you are feeding it also has double quotes throughout that don't look to be escaped. Every time a double quote is encountered it is terminating the string and trying to parse the rest as javascript statements and not a string.
I know this is an old question, but I faced a simmilar problem using will_paginate gem, and I tryed a lot of complicated stuffs to update the pagination. However, I did it with a simple solution, that maybe can help someone else.
In summary, create a partial where you put the call to will_paginate
helper inside a div, and after your ajax request, just render this partial again. For instance:
The _pagination.html.erb
:
<div id="paginate">
<%= will_paginate @results %>
<div>
The your_template.js.erb
(where @results should be available):
$('#paginate').html('j(render "pagination.html.erb")');
That should be enough.
精彩评论