分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

jsonp跨域请求

发布时间:2023-09-06 01:27责任编辑:胡小海关键词:jsjson跨域

跨域是什么?为什么我们需要跨域?

跨域是指浏览器访不能问另外一个网站的脚本,这是由于浏览器的同源策略造成的,同时也是浏览器施加给javascript的安全限制。

但是事实上,用户浏览网站是避免不了跨域请求的,所以才需要跨域来解决这个问题。

我最熟悉的是jsonp跨域:因此先贴上jsonp跨域的例子。

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 ????<meta charset="UTF-8"> 5 ????<title>jsonp跨域</title> 6 </head> 7 <style> 8 ????*{margin:0;padding: 0;list-style: none;} 9 ????#wrap{10 ????????width: 400px;11 ????????margin:100px auto;12 ????????border: 1px solid orange;13 ????}14 ????#wrap #txt{15 ????????width: 398px;16 ????????height: 40px;17 ????????font-size: 20px;18 ????????border: 1px solid orange;19 ????????outline: none;20 ????}21 ????#wrap #ul1{22 ????????width: 393px;23 ????}24 ????#wrap #ul1 li{25 ????????width: 393px;26 ????????height: 40px;27 ????????line-height: 40px;28 ????}29 ????#wrap #ul1 li a{30 ????????display: block;31 ????????text-decoration: none;32 ????????color: #000;33 ????}34 ????#wrap #ul1 li a:hover{35 ????????background: cyan;36 ????????color: #fff;37 ????}38 </style>39 <body>40 ????<div id="wrap">41 ????????<input type="text" ?id="txt">42 ????????<ul id="ul1">43 ????????</ul>44 ????</div>45 </body>46 <script>47 ????//data数据格式:{q: "点", p: false, s: Array(10)}48 ????function callback(data) {49 ????????//console.log(data);50 ????var oUl = document.getElementById(‘ul1‘);51 ????var html = ‘‘;52 ????if (data.s.length) {53 ????????oUl.style.display = ‘block‘;54 ????????for (var i=0; i<data.s.length; i++) {55 ????????????html += ‘<li><a target="_blank" href="http://www.baidu.com/s?wd=‘+data.s[i]+‘">‘+ data.s[i] +‘</a></li>‘;56 ????????}57 ????????oUl.innerHTML = html;58 ????} else {59 ????????oUl.style.display = ‘none‘;60 ????}61 ????62 }63 64 // ‘&cb=callback‘ ?里的callback是回调函数65 66 ????window.onload=function(){67 ????????var txt=document.getElementById(‘txt‘);68 ????????var oUl=document.getElementById(‘ul1‘);69 ????????txt.onkeyup=function(){70 ????????????if(this.value!=‘‘){71 ????????????????var Script=document.createElement(‘script‘);72 ????????????????Script.src=‘http://suggestion.baidu.com/su?wd=‘+this.value+‘&cb=callback‘;73 ????????????????document.body.appendChild(Script);74 ????????????}else{75 ????????????????oUl.style.display=‘none‘;76 ????????????}77 78 ????????};79 ????};80 </script>81 </html>

jsonp跨域相对而言还是简单点,容易理解吧。后续还会更新跨域方面方法。

jsonp跨域请求

原文地址:http://www.cnblogs.com/studyshufei/p/7905342.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved