1. 程式人生 > >jsonp跨域請求

jsonp跨域請求

innerhtml 問題 += outline html www. arr 方法 ctype

跨域是什麽?為什麽我們需要跨域?

跨域是指瀏覽器訪不能問另外一個網站的腳本,這是由於瀏覽器的同源策略造成的,同時也是瀏覽器施加給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跨域請求