認識JSONP

jsonp 全稱是JSON with Paddingjavascript

咱們你們都知道ajax是不能發起跨域請求,如今能夠經過jsonp來彌補ajax的這一缺陷java

經過script標籤的src屬性就能夠實現跨域請求。如(CDN)如今的互聯網調優,引用goole,百度等的經常使用js文件,經過瀏覽器的緩存機制能夠實現互聯網調優。jquery

下面是原生js實現跨域請求,走碼ajax

方式一:
 <script type="text/javascript" src="http://localhost:23415/2012Test/testJasonp.ashx?callback=mycallback"></script><!--這裏的地址指跨域地址-->
方式二: <script type="text/javascript"> function createScript() { var myScript = document.createElement("script"); myScript.setAttribute("type", "text/javascript"); myScript.setAttribute("src", "http://localhost:23415/2012Test/testJasonp.ashx?callback=mycallback"); document.body.appendChild(myScript); } function mycallback(data) { alert(data.msg); } window.onload = function () { document.getElementById("getOtherDomainData").addEventListener("click", function () { createScript(); }); } </script>
<input type="button" id="getOtherDomainData" value="發起跨域請求" />

//testJasonp.ashx返回的數據爲context.Response.Write("mycallback({\"msg\":\"ok\"})");

固然經過jquery就能夠輕易實現jsonpjson

 $(function () {
            $("#jqGetOtherDomainData").click(function () {
                $.ajax({
                    type: "GET", url: 'http://localhost:23415/2012Test/testJasonp.ashx', dateType: "jsonp", jsonp: "mycallback", success: function (data) {
                        alert(data.msg);
                    }
                });
            });

        });
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息