今天给大家出一个GET请求使用的案例,案例中将包含GET请求参数拼接、AJAX异步处理、AJAX解决IE6兼容问题、GET应用场景格式、原生JS获取节点等知识点。

此案例代码将实现输入国家和城市名,传入后端接口去查询,查询到以后展示在前端。本案例主要知识点在原生JS的使用及AJAX的GET传递参数的使用上。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>宗波尘客-GET传递参数案例和GET参数拼接</title>
</head>
<body>
<div id="form">
<label for="country">国家:<input type="text" name="country" id="country"></label>
<label for="city">城市:<input type="text" name="city" id="city"></label>
</div>
<hr>
<div>你查询的国家是:<span id="ipt_country"></span></div>
<div>你查询的城市是:<span id="ipt_city"></span></div>
<br>
<button type="button" id="search">查询</button>
(查询成功后会把你输入的值显示在上方)
<script>
var oSearch = document.getElementById("search"),
oIpt_country = document.getElementById("ipt_country"),
oIpt_city = document.getElementById("ipt_city");
var url = "/statics/demosource/demo_get_json.php";
oSearch.onclick = function () {
var country = document.getElementById("country").value,
city = document.getElementById("city").value;
var query = "country=" + country + "&city=" + city;
var queryURL = url + "?" + query;
// 发起 get 请求
ajaxGet(queryURL);
}
function ajaxGet (url) {
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
var res = JSON.parse(xhr.responseText);
oIpt_country.innerText = res.params.country;
oIpt_city.innerText = res.params.city;
}
}
}
xhr.open("GET", url);
xhr.send();
}
</script>
</body>如何解决AJAX在IE6及以下浏览器兼容性问题呢?
window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");我们可以使用以上代码来模拟!