可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to send a Get
request with cross domain origin with header authentication.
Its working fine in Chrome and Firefox, but I'm having issues in Safari and IE. Also in random cases it returns 401.
<script> var url = 'username:password@anotherdomain.com'; $.ajax({ url: url, dataType: 'jsonp', jsonpCallback: "callback", success: function(json) { alert(json); } }); </script>
What would be the best option to solve this?
回答1:
If I have understood the question correctly, you could use the beforeSend callback to add basic authentication on the request. This is irrelevant of jsonp or cross-origin though.
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); }
https://jsfiddle.net/rn9Lp304/
回答2:
For Internet Explorer 8 and 9
you need to use XDomainRequest Object
Internet Explorer 10+ does the cross domain requests normally like all the other browsers.
As mentioned in the documentation you need to
- create an object of the XDR using
var xdr = new XDomainRequest();
- open the connection using the get method using
xdr.open("get", "username:password@anotherdomain.com");
- send the data back to the server using
xdr.send();
The complete code reference can be shown as on this thread by @Mark Pieszak
as a workaround to set the username
and the password
in the internet explorer you can set the following
DWORD
for iexplore.exe
to 0
in: [HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE]
.
回答3:
I will recommend you to try two things:
In ajaxSetup, do this:
$.ajaxSetup({ ...., xhrFields: { withCredentials: true }, crossDomain: true, .... });
In your ajax requests, set the full url like so, in addition to the credentials flag.
'Access-Control-Allow-Origin: https://not-example.com' 'Access-Control-Allow-Credentials: true'
For servers with authentication, these browsers do not allow "*" in this header. The Access-Control-Allow-Origin header must contain the value of the Origin header passed by the client.
回答4:
use getJSON
$.getJSON("url",function (data) {/*code here*/});