I am going to share the jquery code that I used to invoke a cross domain webservice (for more details on cross domain requests, please click here)
We need to pass following couple of important fields while invoking the cors webservice.
- dataType: 'json'
- crossDomain : true
- and I have the basic authentication as well for my webservice, so I am passing xhrFields.
xhrFields: {
withCredentials: true
}
Here is the full jquery code snippet,
$.ajax({
url:'URL_TO_MY_WEBSERVICE',
headers: {
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Max-Age': '86400',
'Access-Control-Allow-Credentials':true,
'Authorization':setAuthHeader("userName", "password"),
'Content-Type':'application/json'
},xhrFields: {
withCredentials: true
},
type: 'GET',
dataType: 'json',
crossDomain : true
Note: My webservice requires the users to be authenticated with http basic authentication. You can see the Authorization uses a method called setAuthHeader() which intern uses btoa() function to generate the base 64 encoded string which is required for basic authentication. Please find the setAuthHeader() source code below,
function setAuthHeader(username,password){
var cred = username +":"+ password;
var basic = btoa(cred);
var hashstr = "Basic "+basic;
return hashstr;
}