AJAX Cross-Domain Same-Origin Policy limitation

來源:互聯網
上載者:User

摘自:http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

 

AJAX Same-Origin Policy(SOP) limitation:

 

 AJAX prevents cross-domail invokation, there are several ways to by pass this limitation.

 

1. write a proxy on the server side. The SOP limitation only exists only on the javascript side.  While on the side, we can still invoke the other domail url such as via HttpClient

 

2. iFrame ( not sure )

 

3. JSONP(JSON with Padding)

 

the same-origin policy doesn't prevent the insertion of dynamic script elements into the document. That is, you could dynamically insert JavaScript from different domains, carrying JSON data in them.

 

<mce:script type="text/javascript"><!--<br />// This is our function to be called with JSON data<br />function showPrice(data) {<br /> alert("Symbol: " + data.symbol + ", Price: " + data.price);<br />}<br />var url = “ticker.js”; // URL of the external script<br />// this shows dynamic script insertion<br />var script = document.createElement('script');<br />script.setAttribute('src', url);</p><p>// load the script<br />document.getElementsByTagName('head')[0].appendChild(script);<br />// --></mce:script>

 

 

Note that, in order to do this, you must have a callback function already defined in the Web page at the time of insertion.

 

Beginning with version 1.2, jQuery has had native support for JSONP calls. You can load JSON data located on another domain if you specify a JSONP callback, which can be done using the following syntax: url?callback=?.

 

AJAX invoke:

jQuery.getJSON("http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?",<br />function(data) {<br /> alert("Symbol: " + data.symbol + ", Price: " + data.price);<br />});<br />

 

 

Another domain generates json data and returned to client side with callback function.

@Override<br />protected void doGet(HttpServletRequest req, HttpServletResponse resp)<br /> throws ServletException, IOException {<br />String jsonData = getDataAsJson(req.getParameter("symbol"));<br />String output = req.getParameter("callback") + "(" + jsonData + ");";</p><p>resp.setContentType("text/javascript");</p><p>PrintWriter out = resp.getWriter();<br />out.println(output);<br />// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});<br />}<br />

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.