轉自:http://my.oschina.net/LinBandit/blog/33160
今天在研究js調用webservice時發現谷歌一直報:Origin null is not allowed by Access-Control-Allow-Origin
后來查到錯誤原因是:
使用xmlhttprequest獲取服務數據時,在IE下能通過而在 chrome不能通過的問題,這就是所謂的跨域問題,什么是跨域呢?比較不規范但是通俗的說說法吧,比如你使 用chrome打開一個本地的html頁面,那么我認為現在你的機器就是一個站點,這個html就是運行在這個站點上,如果你要在這個html頁面中通過 xmlhttprequest獲取百度的頁面源碼信息,就有點跨域的意思,這和你直接在地址欄上輸入www.baidu.com又不一樣,因為那樣的話, 你當前的站點就是百度了,如果百度也在他的主頁上通過xmlhttprequest獲取google的頁面信息,那樣應該也算是跨域了吧,但是這個跨域問 題在服務器上是不存在的,你在服務器上使用urlHttpConnection連接其他站點是允許的。
可以想象,你連接到你自己的服務器,打開一個頁面,如果這個頁面要獲取google的數據,那么這個頁面可以向服務器發出請求(這個頁面和這個服務 器是同一個域,我通俗的理解,所以這個請求沒問題),服務器根據請求向google獲取數據(這個是允許的),然后服務器再將獲取到的數據反饋回頁面,這 樣頁面就獲取到google的數據了。
具體代碼怎么寫就不在話下啦!
最后可以通過服務器來解決這個問題,但至於為什么IE8可以允許跨域訪問我就不清楚了!
=====================分隔符===============================
加料:
轉自:http://www.cnblogs.com/accessking/archive/2012/05/12.html
在學習XMLHttpRequest的使用過程中,使用chrome打開任意空網頁,在控制台下輸入如下代碼
1 var oHttp=new XMLHttpRequest(); 2 undefined 3 oHttp.open('GET','http://www.baidu.com/') 4 undefined 5 oHttp.send(); 6 undefined 7 XMLHttpRequest cannot load http://www.baidu.com/. Origin null is not allowed by Access-Control-Allow-Origin.
報錯部分的英文的大概意思就是不允許跨域,至於什么叫做不允許跨域呢?
請看上面解釋。
我嘗試了chrome、firfox、opera都出現了這種情況,但是使用IE8就不會出現這種錯誤,很多人不是很理解。
這里Windows help and support 做出了解釋 IE本身也並不是允許跨域的因為這樣很不安全,但是如果不跨域的話又帶來很多不便,所以會讓你手動的選擇一下是否允許跨域。而chrome、firfox、opera則默認就是不允許。
What is active content and why does Internet Explorer restrict it?
Active content is interactive or animated content used on websites. It includes ActiveX controls and web browser add-ons, which are small programs that are used extensively on the Internet. Active content can make web browsing more enjoyable by providing toolbars, stock tickers, video, animated content, and more.
Why does Internet Explorer restrict active content?
Internet Explorer restricts this content because occasionally these programs can malfunction or give you content you don't want. In some cases, these programs can be used to collect information about you, damage information on your computer, install software without your consent, or allow someone else to control your computer remotely. Given these risks, you should allow active content only if you completely trust the publisher or the website it's coming from.
How can I allow active content?
If Internet Explorer restricts active content that you are sure you want to allow, click the gold Information bar that appears at the top of the webpage, and then click Allow blocked content. For more information, see Internet Explorer Information bar: frequently asked questions.