[英]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= helloworld
而helloworld
可能是您故事中的另一個頁面。
對於.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.