筆記-Ajax[4]-JSONP跨域擷取資料。

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

JS的跨域:跨網域名稱擷取資料,a網域名稱擷取b網域名稱中的資料。

解決跨域擷取資料的方法也叫JSONP(JSON and Padding)

JSONP方法:

1:伺服器代理:XMLHttpRequest代理檔案2:script標籤:jsonp(常用);//利用script標籤的src引入外部檔案的功能,src能夠引入任何的檔案的類型3:location.hash方式:iframe4:window.name方式5:flash方式6:html5的postMessage方式

例子:百度輸入資料下拉框提示功能

布局代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><link rel="stylesheet" href="css/index.css" type="text/css" /><script type="text/javascript" src="js/index.js"></script></head><body><input type="text" id="content"/><ul id="lists"></ul></body></html>

css代碼:

#content{width:300px;height:40px;line-height:40px;border:1px solid #ccc;font-size:16px;}#lists{margin:0px;list-style:none;padding:0px;border:1px solid #ccc;width:300px;display:none;}#lists li a{display:block;width:300px;height:35px;line-height:35px;font-size:14px;text-decoration:none;color:#C60;}#lists li a:hover{background:#ccc;}

javascript代碼:

// JavaScript Documentfunction getData(data){    var oUl=document.getElementById("lists");    var listContents="";    if(data.s.length){            oUl.style.display="block";            for(var i=0;i<data.s.length;i++){                listContents+="<li><a href=‘http://www.baidu.com/#wd="+data.s[i]+"&rsv_bp=0&tn=baidu&rsv_spt=3&ie=utf-8&rsv_sug3=4&rsv_sug4=361&rsv_sug1=4&f=3&rsp=0&inputT=3257‘ target=‘_blank‘>"+data.s[i]+"</a></li>";                }            oUl.innerHTML=listContents;    }else{        oUl.style.display="none";    }}window.onload=function(){    var oContent=document.getElementById("content");    var oUl=document.getElementById("lists");    oContent.onkeyup=function(){            if(this.value!=""){                var oScript=document.createElement("script");                oScript.src="http://suggestion.baidu.com/su?wd="+this.value+"&cb=getData";                document.getElementsByTagName(‘head‘)[0].appendChild(oScript);                    }else{                oUl.style.display="none";            }    }}

效果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.