frontend:

first :add $.support.cors=true; in front of the Ajax code.

seconde: add the crossDomain:true, attribute to the $.ajax.

webconfig:

add the following code to the node  <system.webServer>

<httpProtocol>
  <customHeaders>
    <add name="access-control-allow-headers" value="accept, origin, token,content-type" />
    <add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Allow-Methods" value="OPTIONS, GET, POST" />
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

Note:

http->http

https->https

/*
* Copyright (C) 2011 Ovea <dev@ovea.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* https://gist.github.com/1114981
*
* By default, support transferring session cookie with XDomainRequest for IE. The cookie value is by default 'jsessionid'
*
* You can change the session cookie value like this, before including this script:
*
* window.XDR_SESSION_COOKIE_NAME = 'ID';
*
* Or if you want to disable cookie session support:
*
* window.XDR_SESSION_COOKIE_NAME = null;
*
* If you need to convert other cookies as headers:
*
* window.XDR_COOKIE_HEADERS = ['PHP_SESSION'];
*
* To DEBUG:
*
* window.XDR_DEBUG = true;
*
* To pass some headers:
*
* window.XDR_HEADERS = ['Content-Type', 'Accept']
*
*/
(function ($) { if (!('__jquery_xdomain__' in $)
&& /msie/.test(navigator.userAgent.toLowerCase()) // must be IE
&& 'XDomainRequest' in window // and support XDomainRequest (IE8+)
&& !(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()) // and must not support CORS (IE10+)
&& document.location.href.indexOf("file:///") == -1) { // and must not be local $['__jquery_xdomain__'] = $.support.cors = true; var urlMatcher = /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
oldxhr = $.ajaxSettings.xhr,
sessionCookie = 'XDR_SESSION_COOKIE_NAME' in window ? window['XDR_SESSION_COOKIE_NAME'] : "jsessionid",
cookies = 'XDR_COOKIE_HEADERS' in window ? window['XDR_COOKIE_HEADERS'] : [],
headers = 'XDR_HEADERS' in window ? window['XDR_HEADERS'] : ['Content-Type', 'Token'],
ReadyState = { UNSENT: 0, OPENED: 1, LOADING: 3, DONE: 4 },
debug = window['XDR_DEBUG'] && 'console' in window,
XDomainRequestAdapter,
domain,
reqId = 0; function forEachCookie(names, fn) {
if (typeof names == 'string') {
names = [names];
}
var i, cookie;
for (i = 0; i < names.length; i++) {
cookie = new RegExp('(?:^|; )' + names[i] + '=([^;]*)', 'i').exec(document.cookie);
cookie = cookie && cookie[1];
if (cookie) {
fn.call(null, names[i], cookie);
}
}
} function parseResponse(str) {
// str === [data][header]~status~hlen~
// min: ~0~0~
if (str.length >= 5) {
// return[0] = status
// return[1] = data
// return[2] = header
var sub = str.substring(str.length <= 20 ? 0 : str.length - 20),
i = sub.length - 1,
end, hl, st;
if (sub.charAt(i) === '~') {
for (end = i--; i >= 0 && sub.charAt(i) !== '~'; i--);
hl = parseInt(sub.substring(i + 1, end));
if (!isNaN(hl) && hl >= 0 && i >= 2 && sub.charAt(i) === '~') {
for (end = i--; i >= 0 && sub.charAt(i) !== '~'; i--);
st = parseInt(sub.substring(i + 1, end));
if (!isNaN(st) && i >= 0 && sub.charAt(i) === '~') {
end = str.length - hl - sub.length + i;
return [st, str.substring(0, end), str.substr(end, hl)];
}
}
}
}
return [200, str, ''];
} function parseUrl(url) {
if (typeof (url) === "object") {
return url;
}
var matches = urlMatcher.exec(url);
return matches ? {
href: matches[0] || "",
hrefNoHash: matches[1] || "",
hrefNoSearch: matches[2] || "",
domain: matches[3] || "",
protocol: matches[4] || "",
authority: matches[5] || "",
username: matches[7] || "",
password: matches[8] || "",
host: matches[9] || "",
hostname: matches[10] || "",
port: matches[11] || "",
pathname: matches[12] || "",
directory: matches[13] || "",
filename: matches[14] || "",
search: matches[15] || "",
hash: matches[16] || ""
} : {};
} function parseCookies(header) {
if (header.length == 0) {
return [];
}
var cooks = [], i = 0, start = 0, end, dom;
do {
end = header.indexOf(',', start);
cooks[i] = (cooks[i] || '') + header.substring(start, end == -1 ? header.length : end);
start = end + 1;
if (cooks[i].indexOf('Expires=') == -1 || cooks[i].indexOf(',') != -1) {
i++;
} else {
cooks[i] += ',';
}
} while (end > 0);
for (i = 0; i < cooks.length; i++) {
dom = cooks[i].indexOf('Domain=');
if (dom != -1) {
cooks[i] = cooks[i].substring(0, dom) + cooks[i].substring(cooks[i].indexOf(';', dom) + 1);
}
}
return cooks;
} domain = parseUrl(document.location.href).domain;
XDomainRequestAdapter = function () {
var self = this,
_xdr = new XDomainRequest(),
_mime,
_reqHeaders = [],
_method,
_url,
_id = reqId++,
_setState = function (state) {
self.readyState = state;
if (typeof self.onreadystatechange === 'function') {
self.onreadystatechange.call(self);
}
},
_done = function (state, code) {
if (!self.responseText) {
self.responseText = '';
}
if (debug) {
console.log('[XDR-' + _id + '] request end with state ' + state + ' and code ' + code + ' and data length ' + self.responseText.length);
}
self.status = code;
if (!self.responseType) {
_mime = _mime || _xdr.contentType;
if (_mime.match(/\/json/)) {
self.responseType = 'json';
self.response = self.responseText;
} else if (_mime.match(/\/xml/)) {
self.responseType = 'document';
var $error, dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
dom.loadXML(self.responseText);
self.responseXML = self.response = dom;
if ($(dom).children('error').length != 0) {
$error = $(dom).find('error');
self.status = parseInt($error.attr('response_code'));
}
} else {
self.responseType = 'text';
self.response = self.responseText;
}
}
_setState(state);
// clean memory
_xdr = null;
_reqHeaders = null;
_url = null;
};
_xdr.onprogress = function () {
_setState(ReadyState.LOADING);
};
_xdr.ontimeout = function () {
_done(ReadyState.DONE, 408);
};
_xdr.onerror = function () {
_done(ReadyState.DONE, 500);
};
_xdr.onload = function () {
// check if we are using a filter which modify the response
var cooks, i, resp = parseResponse(_xdr.responseText || '');
if (debug) {
console.log('[XDR-' + reqId + '] parsing cookies for header ' + resp[2]);
}
cooks = parseCookies(resp[2]);
self.responseText = resp[1] || '';
if (debug) {
console.log('[XDR-' + _id + '] raw data:\n' + _xdr.responseText + '\n parsed response: status=' + resp[0] + ', header=' + resp[2] + ', data=\n' + resp[1]);
}
for (i = 0; i < cooks.length; i++) {
if (debug) {
console.log('[XDR-' + _id + '] installing cookie ' + cooks[i]);
}
document.cookie = cooks[i] + ";Domain=" + document.domain;
}
_done(ReadyState.DONE, resp[0]);
resp = null;
};
this.readyState = ReadyState.UNSENT;
this.status = 0;
this.statusText = '';
this.responseType = '';
this.timeout = 0;
this.withCredentials = false;
this.overrideMimeType = function (mime) {
_mime = mime;
};
this.abort = function () {
_xdr.abort();
};
this.setRequestHeader = function (k, v) {
if ($.inArray(k, headers) >= 0) {
_reqHeaders.push({ k: k, v: v });
}
};
this.open = function (m, u) {
_url = u;
_method = m;
_setState(ReadyState.OPENED);
};
this.send = function (data) {
_xdr.timeout = this.timeout;
if (sessionCookie || cookies || _reqHeaders.length) {
var h, addParam = function (name, value) {
var q = _url.indexOf('?');
_url += (q == -1 ? '?' : '&') + name + '=' + encodeURIComponent(value);
if (debug) {
console.log('[XDR-' + _id + '] added parameter ' + name + "=" + value + " => " + _url);
}
};
for (h = 0; h < _reqHeaders.length; h++) {
addParam(_reqHeaders[h].k, _reqHeaders[h].v);
}
forEachCookie(sessionCookie, function (name, value) {
var q = _url.indexOf('?');
if (q == -1) {
_url += ';' + name + '=' + value;
} else {
_url = _url.substring(0, q) + ';' + name + '=' + value + _url.substring(q);
}
if (debug) {
console.log('[XDR-' + _id + '] added cookie ' + _url);
}
});
forEachCookie(cookies, addParam);
addParam('_xdr', '' + _id);
addParam('Referer', window.location.href);
}
if (debug) {
console.log('[XDR-' + _id + '] opening ' + _url);
}
_xdr.open(_method, _url);
if (debug) {
console.log('[XDR-' + _id + '] send, timeout=' + _xdr.timeout);
}
_xdr.send(data);
};
this.getAllResponseHeaders = function () {
return '';
};
this.getResponseHeader = function () {
return null;
}
}; $.ajaxSettings.xhr = function () {
var target = parseUrl(this.url).domain;
if (target === "" || target === domain) {
return oldxhr.call($.ajaxSettings);
} else {
try {
return new XDomainRequestAdapter();
} catch (e) {
}
}
}; }
})
(jQuery);

JQuery Cross Domain的更多相关文章

  1. JQuery Cross Domain Ajax(jsonp)

    http://www.pureexample.com/jquery/cross-domain-ajax.html http://www.pureexample.com/ExampleTesterII- ...

  2. 关于ajax跨域请求(cross Domain)

    Cross Domain AJAX主要就是A.com网站的页面发出一个XMLHttpRequest,这个Request的url是B.com,这样的请求是被禁止的,浏览器处于安全考虑不允许进行跨域访问, ...

  3. [cross domain] four approachs to cross domain in javascript

    four approachs can cross domain in javascript 1.jsonp 2.document.domain(only in frame and they have ...

  4. 前端开发各种cross之cross domain

    作为一个苦逼前端开发工程师,不得不面对各种cross,比如面对五花八门的浏览器我们必须cross browser,面对各种终端,我们必须cross device,在这么多年的前端开发经历中,在不同的域 ...

  5. Ajax cross domain

    xhrFields:{ withCredentials:true}, https://stackoverflow.com/questions/2054316/sending-credentials-w ...

  6. 前后端跨域 _ cross domain

    1. 解决跨域既可以从前端, 也可以从后端. 参考好的网络资源: http://www.cnblogs.com/vajoy/p/4295825.html

  7. NodeJS Cross domain

    跨域问题主要在header上下功夫 首先提供一个w3c的header定义 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 再提供一个网友提 ...

  8. jQuery源码分析系列(35) : Ajax - jsonp的实现与原理

    ajax的核心是通过XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加<script>标签来调用服务器提供的js脚本 json核心就是:允许用户传递一个callba ...

  9. jQuery源码 Ajax模块分析

    写在前面: 先讲讲ajax中的相关函数,然后结合函数功能来具体分析源代码. 相关函数: >>ajax全局事件处理程序 .ajaxStart(handler) 注册一个ajaxStart事件 ...

随机推荐

  1. Pyhton 学习总结 20 :执行系统命令

    在Python中执行系统命令有os.system().os.popen().commands.getstatusoutput().subprocess.Popen等     1.os.system() ...

  2. 导入maven工程遇见的问题【问题】

    原工程是一个基于websocket的maven工程(源工程:http://www.cnblogs.com/xdp-gacl/p/5193279.html),把工程导入eclipse后报错.

  3. vs2005水晶报表无法运行在X64机器上

    要下载补丁:CRRedist2005_X64.msi http://download.csdn.net/download/gcy007/7106933

  4. 关于一个新的DOM选择器querySelector

    在传统的javascript中,提到DOM选择器,大家比较熟悉的方式是通过tag,name,id来获取,其实大家都发现如果获取比较复杂的话,用这个方法会很繁琐,这时大家应该都会想到jquery里获取一 ...

  5. hdu 5780 gcd

    题意:给定$x, n$满足$1 \leq x, n \leq 1000000$,求$\sum{(x^a-1,x^b-1)}$对$1e9+7$取模后的值,其中$1 \leq a, b \leq n$. ...

  6. Internship-ZOJ2532(网络流求割边)

    Internship Time Limit: 5 Seconds      Memory Limit: 32768 KB CIA headquarter collects data from acro ...

  7. Just a Hook(HDU1698 线段树的简单应用)

    Just a Hook Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Prob ...

  8. Unity中通过类名字符串取组件类型的方法(Types.GetType用法)

    正常调用Type.GetType取不到组件,因为会先创建实例在获取,而Unity组件无法通过new来创建. 第二种创建方式是通过程序集,具体如下 Assembly.GetExecutingAssemb ...

  9. jquery幻灯片

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  10. android 常见的泄漏内存方法和 leakcanary 使用方法

    虽然VM接管了内存分配和回收,但是人类在解决问题的同时也会重新创造出一些新的问题,所以问题永远都解决不了,就产生各种稀奇古怪的就业机会了(跑题跑不停). 无论各种VM用什么算法管理内存, 造成内存泄漏 ...