跨域的概念
从a站点获取一个页面,这个页面需要访问b站点的资源,就会产生跨域。跨域是浏览器的限制。
注:a站点和b站点的协议、域名、端口任意一个不一样,就会跨域
跨域的解决方案
jsonp
本质是 利用script标签发送请求,就不会有跨域限制
利用script发送请求,客户端定义一个回调函数,给服务器传递函数名称,服务器返回函数的调用,返回的数据包在函数里
- 缺点
只支持get;服务器和客户端都需要做处理;不合适传递大量数据
cors
跨域资源共享,给服务器设置一个响应头,告诉浏览器,哪些资源可以访问。
header("Access-Control-Allow-Origin:*");
设置代理服务器
浏览器请求代理服务器,代理服务器做请求转发,对于浏览器来说,请求的是同一台服务器
打印360的推荐词案例
调用360的接口,显然会发生跨域,可以用jsonp解决
使用artTemplate.js模板
- 引入模板
- 创建模板
- 模板和数据的绑定(返回模板中的内容,是一个字符串)
- 准备模板内容、解析数据
代码
<input type='text' id='search' />
<ul>
</ul>
<!-- 引入模板文件 -->
<script src='./jquery/template-native.js'></script>
<!-- 创建模板 -->
<script type='text/template' id='templateid'>
<!-- 准备模板内容、解析数据 -->
<% for(var i=0;i< result.length ;i++) { %>
<li>
<%=result[i].word%>
</li>
<%}%>
</script>
<script>
function getInfo(obj) {
// console.log(obj.result);
// 数据和模板进行绑定,返回一个字符串
var html = template("templateid", obj)
// console.log(html);
//添加到页面
document.querySelector('ul').innerHTML = html
}
let search = document.querySelector('#search')
search.onkeyup = function() {
// console.log(this.value);
let script = document.createElement('script')
//360提供的接口
script.src = 'https://sug.so.360.cn/suggest?callback=getInfo&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=' + this.value
document.body.appendChild(script)
}
</script>
</body>