jQuery实现ajax跨域请求
jsonp形式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./jquery.js"></script>
</head>
<style>
* {
padding: 0;
margin: 0;
}
#box {
margin: 100px;
}
#wd {
width: 400px;
height: 40px;
}
#list {
display: none;
width: 400px;
border: 1px solid #ccc;
}
li {
list-style: none;
padding: 5px;
}
a {
text-decoration: none;
color: #333;
}
</style>
<body>
<div id="box">
<input type="text" id="wd">
<ul id="list"></ul>
</div>
<script>
// 原生js写法
var oInput = document.getElementsByTagName('input')[0];
var oList = document.getElementById('list');
// 标签创建形式
// function doJson(data) {
// var dataArr = data.g;
// oList.innerHTML = '';
// if (dataArr.length == 0) {
// oList.style.display = 'none';
// } else {
// dataArr.forEach(function (ele) {
// oLi = document.createElement('li');
// oA = document.createElement('a');
// oA.href = 'https://www.baidu.com/s?wd=' + ele.q;
// oA.innerHTML = ele.q;
// oLi.appendChild(oA);
// oList.appendChild(oLi);
// oList.style.display = 'block';
// });
// }
// }
// 字符串拼接形式
function doJson(data) { // 回调函数处理数据 注意此函数需要写在ajax前面
var dataArr = data.result;
oList.innerHTML = '';
str = '';
if (dataArr.length == 0) {
oList.style.display = 'none';
} else {
dataArr.forEach(function (ele, index) {
if (index > 3) return;
str += '<li><a href="https://www.baidu.com/s?wd=' + ele[0] + ' " target = "_blank">' +ele[0]+ '</a></li>';
});
oList.innerHTML = str;
oList.style.display = 'block';
}
}
oInput.oninput = function () {
var value = this.value;
$.ajax({
url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + value,
type: 'GET',
dataType: "jsonp", // jsonp形式实现跨域
jsonpCallback: 'doJson', //设置回调函数
})
}
</script>
</body>
</html>