【问题标题】:ruby/sinatra handle the ajax request but nothing happensruby/sinatra 处理 ajax 请求但没有任何反应
【发布时间】:2015-03-17 19:16:58
【问题描述】:

我正在尝试使用 AJAX 请求制作一个简单的应用程序,以在同一页面中加载数据。

这是 .rb 代码:

get '/' do 
    erb :index
end

post '/ssearch' do
  if request.xhr?

    keyword = params[:key]
    items = extract_cse_info(keyword)

    erb :ssearch, :locals => { 'items' => items }
  else
    erb :index
  end
end

这里是layout.erb加载的.js文件

$(document).ready(function(){
    $('.SR_title').hide();
    $('#msg').hide();

    $('.SR_box').hover(function(){
        $(this).find('.SR_title').toggle().stop(true, true);
        $(this).toggleClass('SR_box_hover');
    }); 

    $("#searchform").submit(function(){
            var   form = $("#searchform"),
         term = form.find( "input[name='key']" ).val(),
         url  = form.attr("action"); 
         $.ajax({
            type: "POST",
            url: url,
            data: term,
            success: function(msg){
            $('#msg').html(msg);
        }
        });

    });

这里有 index.erb 代码

<div class="search">
    <form method="POST" action="/ssearch" id="searchform">
        <input id="search" type="search" name="key" autocomplete="on" placeholder="search qui..." />
        <button class="submit" type="submit">Go!</button>
    </form>

    <div id="msg"></div>
</div>

和 ssearch.erb 执行一些东西。

<% i = 1 %>
<% items["items"].each do |x| %>
<div class="SR_box">
    <div class="SR_title">
        <h5>Title</h5>
        <a class="SR_box_fs fa fa-arrows-alt" href="#"></a>
    </div>
    <iframe class="iframe" src=<%= "#{x['link']}"%> sandbox="allow-same-origin, allow-top-navigation, allow-forms"></iframe>
</div>
<% end %>

当我得到 / 一切正常,但执行搜索时没有任何反应,浏览器只显示没有在 ssearch.erb 中创建的框架的表单。为什么? 只是提示会显示一条服务器错误消息:

http://localhost:4567 -> /ssearch NoMethodError - nil:NilClass 的未定义方法“每个”: ssearch.erb:2:in 'block in singletonclass'`

【问题讨论】:

    标签: jquery ruby ajax sinatra


    【解决方案1】:

    哦哦哦,问题很简单(现在)。

    Sinatra 不接受 jquery ajax 请求中 'data:' 参数中的变量,您必须以这种方式明确地编写(在我的情况下):

    data: { term: form.find("input[name='key']" ).val()},
    

    之前写的:

     term = form.find( "input[name='key']" ).val(),
    ...
    data: term,
    

    然后我用这种方式稍微修改 .rb 文件:

     @keyword = params[:term]
        puts "keyword is  #{@keyword}"
        @items = extract_cse_info(@keyword)
       puts @items
    
        erb :ssearch, :layout => false
    

    现在我在七天堂,我喜欢成为这种情感的新手:)

    再见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多