AJAX XML跨域调用[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/3076414/ways-to-circumvent-the-same-origin-policy" dir="ltr">Ways to circumvent the same-origin policy</a>
                            <span class="question-originals-answer-count">
                                (11 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2013-06-19 18:28:07Z" class="relativetime">6 years ago</span>.</div>
        </div>
    </aside>

Recently I came across the following statement: "All Ajax calls to an XML data file must come from the same domain or the request will fail.", can anyone help me understanding this since I can't make much out of it.

</div>

Let's say your site, including the Javascript that will start the AJAX is hosted at site1.com.

The AJAX will request a file called file.xml whose address is site2.com/file.xml.

This request site1.com ---> site2.com voilates the same origin policy because the 2 are on a different domain.

The way around this?

  • Easiest solution is to host file.xml on site1.com, if you can?
  • You can request a URL on your domain site.com/getMeThatAwesomeFile which executes some server side code to grab the file's contents and returns it to you
  • You can use a reverse proxy so site2.com/file.xml actually resolves to something on your domain.

You can use JSONP but there are some limitations (Only 'GET' verbs allowed and data should be placed inside the function from server). The very first thing JSONP is not an ajax call, it downloads the script and calls the jsonp function and in that function the data is passed.

e.g. If you use JSONP, then it would be like

<script type='text/javascript' src='cross-domain-url'>jsonpFunction(data)</script> 

From the server, you must get the response like jsonpFunction({'name':'abc'}), so after getting this response, your declared jsonpFunction will be called and you will be able to achieve this {'name':'abc'} object.