您的位置:首页 > Web前端 > JavaScript

实践:jsonp实现跨域访问

2016-12-05 17:43 337 查看
跨域问题有三种解决方法,今天主要为大以JSONP方式实现跨域请求。

jsonp实现跨域原理使用的script标签,因为script没有跨域问题,我们前端有时候写一些插件时候,引用在线的 JQ ,这就是跨域的访问使用。

下面附一篇实例;

jsonp实现 百度搜索

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Jsonp解决跨域问题</title>
<style>
*{
margin: 0;
padding: 0;
}
.section{
width: 641px;
margin: 30px auto;
}
#W{
width: 540px;
height: 36px;
text-indent: 1em;
}
#ul{border:1px solid dodgerblue; width: 541px; display: none;list-style: none;}
li a { line-height: 30px; padding: 5px; text-decoration: none; color: black; display: block;}
li a:hover{ background: dodgerblue; color: white; }
</style>
<script>
function J(data){
var oUl = document.getElementById('ul');
var html = '';
console.log(data);
if (data.s.length) {
oUl.style.display = 'block';
for (var i=0; i<data.s.length; i++) {
html += '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>';
}
oUl.innerHTML = html;
} else {
oUl.style.display = 'none';
}
}
window.onload=function(){
var oSearch=document.getElementById("search");
var oUl = document.getElementById('ul');
var oW=document.getElementById("W");
oSearch.onclick=function(){
if(oW.value!=""){
console.log(oW.value);
var oScript=document.createElement("script");
oScript.src = 'http://suggestion.baidu.com/su?wd='+oW.value+'&cb=J';
document.body.appendChild(oScript);
}
else{
oUl.style.display = 'none';
}
}
}
</script>
</head>
<body>
<div class="section">
<input type="text" id="W"/>
<input type="button"  id="search" value="搜索"/>
<ul id="ul"></ul>
</div>
</body>
</html>



接下来我会用自己搭载的服务器,为大家实现跨域请求实践。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jsonp 实例