1

我有一个表单,用户将使用它来输入书名,我将把它传递给外部图书搜索 API,然后我想在不重新加载页面的情况下在下方显示图书结果。

新的.html.haml

(输入标题的表格)

= form_tag book_search_path, :method => :get, :remote => true do
    = label_tag "Title: (#{@title})"
    = text_field_tag "title", ""
    = submit_tag "Search!"

#results // results should be updated here

book_controller.rb

(book_search_path 到这里,到 'search' 动作)

class BooksController < ApplicationController

def index
    @books = Book.find :all
    render :action => 'list'
end 

def new 
    @books = Book.find :all
end 

def search
    Rails.logger.info("DOSEARCH!!!")
    # HIT THE API
    @results = search_keywords params[:title]
    # implicit render search.js.erb
end

搜索.js.erb

(在书籍#search 操作结束时呈现)

m = $('#results');    
m.innerHTML = "<%= escape_javascript(render :partial => 'results.html.haml') %>";

_results.html.haml

(这是我想通过 ajax 插入结果 div 的内容)

- @results.each do |b| 
  %tr 
    %td 
      - Rails.logger.info("Got title...#{b.title}")
      = b.title
    %td 
      = b.isbn

我知道它_results.html.haml正在运行,因为我看到了“得到标题”日志,但它没有显示在resultsdiv 内的 new.html.haml 上。知道发生了什么吗?

编辑:更新 books_controller。带有完整的代码。Book.rb 是一个空模型,除了 :attr_accessible 字段

编辑:阿贾克斯响应:

m = $('#results');    
m.innerHTML = "<table id=\'results_table\'>\n  <tbody><\/tbody>\n  <th>Title<\/th>\n  <th>ISBN<\/th>\n  <tr>\n    <td>\n      The Odyssey\n    <\/td>\n    <td>\n      \n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey of Homer\n    <\/td>\n    <td>\n      1604240687\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey\n    <\/td>\n    <td>\n      1613821166\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey of Homer\n    <\/td>\n    <td>\n      1437818080\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      Odyssey\n    <\/td>\n    <td>\n      0872204847\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey (Penguin Classics)\n    <\/td>\n    <td>\n      0143039954\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey: The Fitzgerald Translation\n    <\/td>\n    <td>\n      0374525749\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey\n    <\/td>\n    <td>\n      1613823398\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey\n    <\/td>\n    <td>\n      0763642681\n    <\/td>\n  <\/tr>\n  <tr>\n    <td>\n      The Odyssey (Penguin Classics)\n    <\/td>\n    <td>\n      0140449116\n    <\/td>\n  <\/tr>\n<\/table>\n";

编辑:这是 Rails 3.2.8

4

1 回答 1

2

尝试将以下块添加到您的search操作中:

respond_to do |format|
  format.js
end

另外,将行替换search.js.erb为如下所示:

$('#results').html("<%= escape_javascript(render :partial => 'results') %>");

更新

看起来真正的问题(假设没有其他语法问题)是不是所有浏览器都支持innerHTML(参见this

于 2012-09-07T23:00:24.970 回答