【问题标题】:inject html using ajax使用ajax注入html
【发布时间】:2011-03-31 13:50:06
【问题描述】:

我有一个包含一些 div 元素的 HAML 页面。单击按钮时,我需要将其注入另一个页面上的 div 中。我该怎么做呢?谢谢

【问题讨论】:

  • 您想使用什么技术? javascript和python?
  • ajax/javascript...使用 rails (mvc)

标签: html ajax haml


【解决方案1】:

您必须从 jQuery.com 添加 jQuery 插件。您可以下载插件或使用链接 http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js作为js文件中的src。

然后使用以下代码

$(document).ready(function(){
  $("#your_button_Id").click(function(){
    $.ajax({
      url: "test.html",
      context: document.body,
      success: function(response){
        $('#div_Id').html(response);
      }
    });
  });
});

希望这会有所帮助!!! 快乐编码。

【讨论】:

  • 当我使用此代码时,它会加载页眉/页脚等,而不仅仅是我的 html 文件中的内容(即只有 div)。 html文件没有任何页眉/页脚等......有什么想法吗?
  • @newbie_86 您的 Haml 使用什么 Web 框架? (Sinatra、Rails、...?)您需要关闭请求的布局,或仅使用该 Haml 模板的部分布局。
  • 你实际上可以像任何你想要的那样从服务器发送响应,而不是发送完整的 html。
【解决方案2】:

如果你想使用 jquery,试试 $('div').load('lol.HTML')

【讨论】:

    【解决方案3】:

    为简化此过程,请将jQuery library 添加到您的页面。

    下面是一个使用jQuery从不同页面加载数据到当前页面的例子:

    inject_to = $("div#id"); // the div to load the html into
    load_from = "/some/other/page"; // the url to the page to load html from
    data = ""; // optional data to send to the other page when loading it
    
    // do an asynchronous GET request
    $.get(load_from, data, function(data)
    {
        // put the received html into the div
        inject_to.html(data);
    }
    

    请注意,这会针对安全/xss 问题打开,我建议使用 .text 而不是 .html,并且仅从外部页面加载纯文本。更多关于 jQuery ajax 的信息:http://api.jquery.com/category/ajax/

    要在单击按钮时执行此操作,请将上述代码放入函数中,如下所示:

    function buttonClicked()
    {
        inject_to = $("div#id"); // the div to load the html into
        load_from = "/some/other/page"; // the url to the page to load html from
        data = ""; // optional data to send to the other page when loading it
    
        // do an asynchronous GET request
        $.get(load_from, data, function(data)
        {
            // put the received html into the div
            inject_to.html(data);
        }
    }
    

    然后给按钮添加点击事件的事件处理函数,像这样:

    $("button#id").click(buttonClicked);
    

    更多关于 jQuery 事件的信息:http://api.jquery.com/category/events/

    【讨论】:

    • 注入时,如何让它用注入的内容覆盖该div的内容?
    • 使用 .html 函数时,它总是会覆盖内容。
    • 它并没有为我覆盖它......只是似乎在注入的内容下方添加了之前的内容
    • 我在我的 haml #myDiv= @lineItems.last.my_field.to_s.html_safe 和 ajax 中有这个:$.ajax({ url: "myTestUrl", context: document.body,成功:function(response){ $('#myDiv').html(response); } });
    • 那很奇怪,你能不能把经过haml处理后的html也贴出来?也许 haml 正在制作格式错误的 html。
    猜你喜欢
    • 2010-10-26
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2010-12-28
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多