首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用ajax注入html

使用ajax注入html
EN

Stack Overflow用户
提问于 2011-03-31 21:50:06
回答 3查看 8.8K关注 0票数 0

我有一个包含一些div元素的HAML页面。当一个按钮被点击时,我需要把它注入到另一个页面的div中。我该怎么做呢?谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-03-31 22:26:32

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

然后使用下面的代码

代码语言:javascript
运行
复制
$(document).ready(function(){
  $("#your_button_Id").click(function(){
    $.ajax({
      url: "test.html",
      context: document.body,
      success: function(response){
        $('#div_Id').html(response);
      }
    });
  });
});

希望这能有所帮助!祝你编码愉快。

票数 2
EN

Stack Overflow用户

发布于 2011-03-31 22:16:01

如果要使用.load,请尝试$(‘div’) jquery (‘lol.HTML

票数 0
EN

Stack Overflow用户

发布于 2011-03-31 22:37:18

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

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

代码语言:javascript
运行
复制
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/

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

代码语言:javascript
运行
复制
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);
    }
}

然后将click事件的事件处理程序添加到按钮,如下所示:

代码语言:javascript
运行
复制
$("button#id").click(buttonClicked);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5500932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档