我需要等效的.load()到JS
我正在开发一个脚本,但我不能使用jQuery库,因此我需要在JS中使用等效的.load()。
我需要在没有jQuery的情况下这样做:
$(document).ready(function(){ $('#a').click(function(){ $('body').append('') $('#b').load('x.html') }); });
谢谢!
function load(url, element) { req = new XMLHttpRequest(); req.open("GET", url, false); req.send(null); element.innerHTML = req.responseText; }
用法
load("x.html", document.getElementById("b"));
简单的答案是,如果没有像jQuery这样的库,你正在做一些相当复杂的事情。 这是“有效”的东西,但没有错误检查或跨浏览器的完美。 你可能真的不想要这个…但是在这里。
load
如果你想在没有JS的情况下这样做,我认为这会对你有所帮助,在#b
添加它
var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else { xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); } /* If you wanted post too */ // xmlhttp.open("POST", "/posturl", true); // xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value"); xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */); xmlhttp.send(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { window.alert(xmlhttp.responseText); } }
异步XMLHttpRequest:
function load(url, element) { req = new XMLHttpRequest(); req.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: element.innerHTML = req.responseText; } }; req.open("GET", url, true); req.send(null); }
用法:
load("x.html", document.getElementById("b"));
这将加载“x.html”并将其放在元素中。