原始Ajax与jQuery中的Ajax
原始Ajax与jQuery中的Ajax
首先通过实例,来看一下 jQuery 实现 Ajax 有多简单。下面是一个使用原始 Ajax 的示例:
<!doctype html><html><head>
<meta charset="utf-8"/>
<title>jQuery Ajax</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function() { var xhr = new AjaxXmlHttpRequest();
$("#btnAjaxOld").click(function(event) { var xhr = new AjaxXmlHttpRequest();
xhr.onreadystatechange = function() { if (xhr.readyState == 4) { document.getElementById("divResult").innerHTML = xhr.responseText;
}
} //由于涉及到同源策略,需要服务器端的支持
xhr.open("GET", "data/AjaxGetCityInfo.aspx?resultType=html", true);
xhr.send(null);
});
}); //跨浏览器获取 XmlHttpRequest 对象
function AjaxXmlHttpRequest() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) { // Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser nonsupport AJAX!"); return false;
}
}
} return xmlHttp;
} </script></head><body>
<button id="btnAjaxOld">original ajax call</button>
<div id="divResult"></div>
</body>
</html>上面的实例中,data/AjaxGetCityInfo.aspx?resultType=html地址会返回一段 HTML 代码。
使用原始 Ajax,我们需要做较多的事情,比如创建XmlHttpRequest对象,判断请求状态,编写回调函数等。
而用 jQuery 的Load方法,只需要一句话:
$("#divResult").load("data/AjaxGetCityInfo.aspx", { "resultType": "html" });现在只是用 jQuery 的 Ajax 函数, 我的页面变得简洁了:
<!doctype html><html lang="zh"><head>
<meta charset="utf-8"/>
<title>jQuery Ajax</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function() {
$("#btnAjaxJquery").click(function(event) {
$("#divResult").load("data/AjaxGetCityInfo.aspx", { "resultType": "html" });
});
})
</script></head><body>
<button id="btnAjaxJquery">use jQuery load method</button>
<div id="divResult"></div>
</body>
</html>

学习ing
原生ajax比jq的ajax复杂多了
8年前 添加回复 0