سؤال

i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use

function createCORSRequest(method, url) {
                var xhr = new XMLHttpRequest();
                if ("withCredentials" in xhr) {
                    // XHR for Chrome/Firefox/Opera/Safari.
                    xhr.open(method, url, true);
                } else if (typeof XDomainRequest != "undefined") {
                    // XDomainRequest for IE.
                    xhr = new XDomainRequest();
                    xhr.open(method, url);
                } else {
                    // CORS not supported.
                    xhr = null;
                }
                return xhr;
            }


            function makeCorsRequest() {
                // All HTML5 Rocks properties support CORS.
      //          var url = 'http://updates.html5rocks.com';

               var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
                var xhr = createCORSRequest('GET', url);
                if (!xhr) {
                    alert('CORS not supported');
                    return;
                }

                // Response handlers.
                xhr.onload = function() {
                    var text = xhr.responseText;
                    console.log(text);
                };

                xhr.onerror = function() {
                    alert('Woops, there was an error making the request.');
                };

                xhr.send();
            }

but the problem still not solved:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work? thanks

هل كانت مفيدة؟

المحلول

For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.

CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.

If the owner of the content doesn't want you to use it, the browser will reject it.

Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top