How to use dataType: 'jsonp' but still hav

2019-02-24 08:06发布

问题:

I want to access a REST service on another domain. If, in JQuery, I specify:

dataType: 'json'

it fails, as expected, since for cross-domain calls, JSONP must be used instead.

When I change this to:

dataType: 'jsonp'

it is expected to work, but fails because the server expects application/json or application/xml or text/html, etc., but not */*, sent by the JSONP request.

Is there a way to force JQuery to put application/json in Accept request header while doing a JSON request?

回答1:

AFAIK jQuery's implementation of JSONP uses a <script> tag that is injected into the DOM (thus the restriction to the GET verb only) for which you cannot control the Accept request content type header. The src of this script tag is simply pointed to the remote domain url. It is the browser that simply fetches the underlying endpoint sending a regular GET request.

So if you want to be able to set request headers for cross domain calls you will have to setup a server side script on your domain that will delegate the call to the remote domain (and set the respective headers) and then send the AJAX request to your script.



回答2:

I think you will want to try something along these lines:

$.ajax({
    headers: { 
        Accept : "application/json; charset=utf-8",
        "Content-Type": "text/plain; charset=utf-8"
    }
    dataType: 'jsonp',
    success : function(response) {
        ...
    }
})


回答3:

This may not be suitable for your use case, but when I have had to do cross-domain AJAX, I would typically just add an additional resource within my domain which would then call the external resource (via cURL or whatever) and return the value to the calling client. In essence you are building a proxy for the AJAX call. It is certainly more overhead, but you may be able to mitigate that by adding a caching layer for such calls.