inject html using ajax

点点圈 提交于 2019-12-12 02:38:01

问题


I have a HAML page with some div elements. I need to inject this into a div on another page when a button is clicked. how do i do this? thanks


回答1:


You have to add the jQuery plugin from jQuery.com. you can download the plugin or use the link http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js as src in the js file.

then use the follwing code

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

Hope this helps!!! happy coding.




回答2:


try $('div').load('lol.HTML') if you want to use jquery




回答3:


To simplify this process, add the jQuery library to your page.

Below is an example of using jQuery to load data from a different page into the current page:

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);
}

Note that this opens for security/xss issues, and I would recommend using .text instead of .html, and load only plain text from the external page. More info on jQuery ajax: http://api.jquery.com/category/ajax/

To do this when a button is clicked, put the above code into a function, like this:

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);
    }
}

Then add an event handler for the click event to the button, like this:

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

More info on jQuery events: http://api.jquery.com/category/events/



来源:https://stackoverflow.com/questions/5500932/inject-html-using-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!