使用ajax注入html

使用ajax注入html,html,ajax,haml,Html,Ajax,Haml,我有一个带有一些div元素的HAML页面。我需要在单击按钮时将其插入另一页上的div中。我该怎么做?谢谢试试$('div')。加载('lol.HTML')如果你想使用jquery你必须从jquery.com添加jquery插件。您可以下载插件或使用链接 作为js文件中的src 然后使用下面的代码 $(document).ready(function(){ $("#your_button_Id").click(function(){ $.ajax({ url: "test.

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

试试$('div')。加载('lol.HTML')如果你想使用jquery

你必须从jquery.com添加jquery插件。您可以下载插件或使用链接 作为js文件中的src

然后使用下面的代码

$(document).ready(function(){
  $("#your_button_Id").click(function(){
    $.ajax({
      url: "test.html",
      context: document.body,
      success: function(response){
        $('#div_Id').html(response);
      }
    });
  });
});
希望这有帮助!!!
快乐编码。

要简化此过程,请将添加到页面中

下面是使用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的更多信息:

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

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);
然后将click事件的事件处理程序添加到按钮,如下所示:

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事件的更多信息:

您想使用什么技术?javascript和python?ajax/javascript…使用rails(mvc)当我使用这段代码时,它会加载页眉/页脚等,而不仅仅是html文件中的内容(即仅div)。html文件没有任何页眉/页脚等…有什么想法吗?@newbie_86您的Haml使用的是什么Web框架?(Sinatra、Rails等?)您需要关闭请求的布局,或者仅使用Haml模板的一部分。您实际上可以根据需要从服务器发送响应,而不是发送完整的html。注入时,我如何让它用注入的内容覆盖该div的内容?当使用.html函数时,它将始终覆盖该内容。它不会为我覆盖它…只是似乎在注入的内容下面添加了以前的内容。我在haml#myDiv=@lineItems.last.my_字段中有这个字段。to_s.html_safe和ajax作为如下:$.ajax({url:“myTestUrl”,context:document.body,success:function(response){$('#myDiv').html(response);}});这很奇怪,你能在haml处理完html后也发布它吗?也许haml正在生成格式错误的html。