1. 程式人生 > >前端 - jsonp 跨域ajax

前端 - jsonp 跨域ajax

ajax pan () 數據信息 技術 提取 遠程 ron 獲取

jsonp 跨域ajax原理:

  瀏覽器同源策略限制

如何解決同源策略限制:  

  方式一:

    利用創建script塊,在其中執行src屬性為 遠程url
        異域 用函數(返回值) 的形式返回參數  

  方式二:

    jquery方式
    異域 用函數(返回值) 的形式返回參數


HTML代碼

    {#html代碼開始#}
        <input type="text" name="k3" value="123">
        {#利用script塊方式#}
        <input type="button" onclick
="b1()" value="提交1"> {#jquery 方式#} <input type="button" id="bt" value="提交2"> {#html代碼結束#}

js代碼

    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        {#利用script塊方式#}
         function b1() {
            var tag = document.createElement("script");
            tag.src 
= "http://172.16.3.107:9999/jsonp?callback=func"; document.head.appendChild(tag); document.head.removeChild(tag); } {#jquery 方式#} $(‘#bt‘).click(function () { $.ajax({ url:‘http://172.16.3.107:9999/jsonp/‘, type:
‘GET‘, dataType:‘jsonp‘, jsonp:‘callback‘, jsonpCallback:‘func‘ })}); {#定義包裹的函數,從而獲取包裹的數據信息#} function func(arg) { console.log(arg) } </script>

別人網站設置

  將返回的數據用函數包裹(這裏包括的函數從get中提取)

技術分享圖片

前端 - jsonp 跨域ajax