jQuery XML REST Access-Control-Allow-Origin

2019-01-19 14:45发布

问题:

I am calling Version One REST API and keep getting XMLHttpRequest cannot load https://www10.v1host.com/... Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. javascript error. I am sending GET request and XML content is expected to be returned in response. This is my jQuery code:

$.ajax({
  dataType: "xml",
  url: "https://www10.v1host.com/...",
  success: function(data, status, xhr) {
  alert("Load was performed.");
  }
});

I have changed dataType: "jsonp" and with this I get response in this format:

jsonp1294354293197(<?xml version="1.0" encoding="UTF-8"?><Asset ...</Asset>)

But get another javascript error: "Uncaught SyntaxError: Unexpected token <"

Is there a way how to get cross domain XML rest data (something like XMLp) or do a workaround for jsonp (prevent parsing JSON format and use my own - parse XML)?

回答1:

You can't do a cross domain XMLHttpRequest, period. As for your own parse XML - that would be only possible if you could get an escaped string instead of bare XML from server. There is no magical parse JSON - JSONP technique just requests another script dynamically adding <script src=...> to header, everything inside is treated as normal JavaScript.



回答2:

It is not possible as long as the server of the REST API (not your server) allows the request from a different origin by setting the CORS (Cross-Origin Resource Sharing) HTTP header, for example by setting the "Access-Control-Allow-Origin" HTTP header in the response:

Access-Control-Allow-Origin: *

or

Access-Control-Allow-Origin: http://localhost:8080

However what you can do is call your own server with Ajax, then use your own server as a kind of proxy to make a call to the other server in a different domain, parse the XML or HTML result with a suitable parser, and give the result back to the client:

 client --(Ajax)--> server
                    server --(HTTP)---> Site 
                    server <----------
 client <----------


回答3:

i know it's an old question but i think there is an better answer, via jQuery documentation:

dataType

multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.