我的本地局域网(machineA)上有一台有两台Web服务器的机器.第一个是XBMC中的内置版(在端口8080上)并显示我们的库.第二个服务器是CherryPy python脚本(端口8081),我用它来按需触发文件转换.文件转换由来自XBMC服务器提供的页面的AJAX POST请求触发.
jQuery Ajax请求
$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
Run Code Online (Sandbox Code Playgroud)
请求标题 - 选项
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://machineA:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
Run Code Online (Sandbox Code Playgroud)
响应标题 - 选项(状态= 200 OK)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:40:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
Run Code Online (Sandbox Code Playgroud)
为了排除故障,我还从http://jquery.com发出了相同的$ .post命令.这是我难倒的地方,从jquery.com开始,post请求有效,OPTIONS请求由POST发送.此交易的标题如下;
请求标题 - …
我需要使用foursquare API来搜索场地.当然它是跨域的.
它在Firefox中没有任何问题,但在Internet Explorer中(7,8,9我测试过).
我的javascript代码如下:
searchVenues: function(searchQuery) {
$.ajax({
url: 'https://api.foursquare.com/v2/venues/search',
data: {
sw: bound_south_west,
ne: bound_north_east,
query: searchQuery.query,
oauth_token: FSQ_OAUTH_TOKEN,
limit: 25,
intent: 'browse',
v: 20120206
},
cache: false,
dataType: 'json',
success: function(data) {
displayResults(data, searchQuery.query);
},
error: function(xhr, status, errorThrown) {
console.log(errorThrown+'\n'+status+'\n'+xhr.statusText);
}
});
}
Run Code Online (Sandbox Code Playgroud)
在Firefox中,它可以完美地显示接收的数据.在Internet Explorer中,它在控制台上登录:
No Transport
Error
Error
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
更新:我强烈建议不要在XDomainRequest中投入任何时间,因为它是一个非常糟糕的实现,有很多限制.它基本上只适用于对非ssl服务器的GET请求,所以你不妨使用jsonp或其他什么.
我使用CORS来调用跨域API,但Internet Explorer提出了问题.通过XDomainRequest对象在IE8和IE9中应该可以使用CORS ,但是我无法使用它.
JQuery 拒绝为XDomainRequest提供本机支持,但是建议使用几个jQuery插件来添加此支持.本主题提出了两个这样的插件:jQuery.XDomainRequest.js和xdr.js,已经报告可以使用.Afaik,插件应该自动覆盖行为jQuery.ajax.我在这里找到了另一个插件.
我把一些演示页面与相应的插件jQuery.XDomainRequest以及xdr和jquery.ie.cors放在一起,它们对启用CORS的服务器执行ajax请求.这些页面在Chrome和Firefox中运行,但IE8/9会立即抛出权限被拒绝错误(甚至在发出请求之前).这个MSDN帖子建议添加另一个处理程序,xhr.onprogress = function() {};但我尝试了这个,它也没有工作.
什么线索我做错了什么?我现在也使用MS8虚拟服务器测试IE8,但它有完全相同的问题.
编辑:好的所以我发现问题的一部分是我通过HTTPS使用POST.显然XDomainRequest不允许通过HTTPS使用CORS.我可以切换到HTTP,但我真的需要POST.
编辑2:在本故事结束时,请在github上查看此问题.事实证明,当使用HTTP POST时,xDomainRequest只能将请求体(参数)编码为text/plain.这几乎使它变得毫无价值,因为每个人都使用application/x-www-form-urlencoded或multipart/form-data.
我被卡住了. 说真的...... - 解决了.请继续阅读:)
场景:我想在这里做正确的事情.我依靠Thinktecture Identitymodel CORS DelegatingHandler将CORS功能添加到我的REST服务(ASP.NET Web-API).到现在为止还挺好.
为了实际测试它是否正常工作,我做了以下事情:
所以我出去看了Fiddler跟踪和IIS日志.Fiddler说没有GET/rest/hello请求,而是一个OPTIONS/rest/hello请求 - 这完全没问题且预期!但是对OPTIONS请求的响应相当有趣!
整个响应头看起来像这样:
HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/7.5
Public: OPTIONS, TRACE, GET, HEAD, POST
Date: Fri, 15 Feb 2013 14:09:27 GMT
Content-Length: 0
Run Code Online (Sandbox Code Playgroud)
这当然远不及预期的反应.有趣的是,请求甚至没有在我的应用程序中命中Application_BeginRequest().所以我的应用程序无法对该结果负责.我可以在我的IIS日志中看到请求,IIS添加了Powered-by-ASP.NET标头..因此它肯定会通过(右侧)IIS站点.
触发ajax请求的JQuery代码:
function Run()
{
$.ajax({
type: 'GET',
url: url,
dataType: "json",
beforeSend: function(jqXhr) {
jqXhr.setRequestHeader("Authorization", "Basic " + getBasicHttpEncodedString(userName, password));
jqXhr.setRequestHeader("Api-Key", "123");
},
success: successCallback, …Run Code Online (Sandbox Code Playgroud) 我想访问来自相同域但具有不同端口号的信息,为了允许这一点,我添加Access-Control-Allow-Origin了响应头.
Servlet代码:(发布在www.example.com:PORT_NUMBER)
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS
response.getWriter().write(json);
Run Code Online (Sandbox Code Playgroud)
jQuery代码:(发布于www.example.com)
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'}).done(function(data)
{
alert(data);
});
Run Code Online (Sandbox Code Playgroud)
有几次我收到这个错误(在控制台中):
XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
此错误通常$.post在执行时第一次出现.第二次它允许.
我的问题是有缺少servlet或jQuery代码?
任何建议将不胜感激.
UPDATE1
我改变了:
response.setHeader("Access-Control-Allow-Origin", "*");
Run Code Online (Sandbox Code Playgroud)
至:
response.setHeader("Access-Control-Allow-Origin", "http://www.example.com");
Run Code Online (Sandbox Code Playgroud)
然后我在控制台中收到此错误:
XMLHttpRequest cannot load http://www.example.com:PORT_NUMBER/MyServletName
The 'Access-Control-Allow-Origin' whitelists only 'http://www.example.com'
Origin 'http://www.example.com' is not in the list,
and is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
[注意:白名单和原点相同,但仍然会出错.它有时会起作用,并且有时会出现上述错误.]
如果您需要更多信息,请与我们联系.
我遇到了IE(11)的奇怪问题.我有简单的jQuery代码:
$("#my-radio").click(function () {
$.ajax({
url: "/my-url",
}).error(function(jqXHR, textStatus, errorThrown) {
$("#error-summary").text(errorThrown);
});
});
Run Code Online (Sandbox Code Playgroud)
问题是这个代码在IE以外的所有浏览器中都能完美运行(在我的情况下除了IE 11,还没有在早期版本中测试)但是,当我打开IE内置的javascript调试器看看有什么问题 - 一切都开始工作了罚款.IE对控制器动作进行ajax调用,控制器中的断点被命中.动作不返回任何东西(它的类型void),只计算一些东西.我已经尝试过在这个帖子中提供的插件解决方案,但它没用.
更新:
为了演示这个问题,我在这里发布了简单的MVC应用程序.当您单击图像时,浏览器会对此操作发出ajax请求:
public string Hello()
{
string ip = Request.ServerVariables["REMOTE_ADDR"];
string agent = Request.UserAgent;
var request = new Request
{
IP = ip,
Time = DateTime.UtcNow,
UserAgent = agent
};
_requestsRepository.Add(request);
int byIp = _requestsRepository.GetTotalRequestsCountByUser(ip);
int total = _requestsRepository.TotalRequests;
string message = string.Format("Hello, {0}. This is your {1}th request and {2}th request in total.", …Run Code Online (Sandbox Code Playgroud) 我一直在IE 9中运行此代码而没有运气.我查看了有关UTF-8修复的所有帖子,但无济于事.有什么想法吗?
$.get({
url: 'http://api.flickr.com/services/rest/?api_key={apikey}&method=flickr.collections.getTree&user_id=66970820%40N03&collection_id=66947766-72157631850748939',
success: function () {
console.log('success!');
}
}).done(function () {
console.log('done');
}).fail(function () {
console.log('fail')
});
Run Code Online (Sandbox Code Playgroud)
它在Safari,FF和Chrome中运行得很好.将URL粘贴到IE中时,响应很好.
我们正在开发一个使用html5,jQuery(1.8.2)和jQuery mobile的移动网站,同时进行jQuery ajax调用(get和post).
在我们更改了域名后,我们对ie9上的ajax调用进行了"拒绝访问".
我们试图包括jquery.iecors.js.但我们仍然得到同样的错误.这有什么解决方案吗?
示例代码:
$.support.cors = true;
$.ajax({
cache: false,
async: true,
crossDomain: true,
timeout: 600000,
url: baseUrl + '/SmartTouch/restServices/PrefferedHotels',
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + myencoded);
},
contentType: "application/x-www.form-urlencoded; (http://www.form-urlencoded;) (http://www.form-urlencoded;) charset=UTF-8",
success: function (data) {
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error!!::" + JSON.stringify(jqXHR));
alert('response: ' + jqXHR.responseText);
alert('code: ' + jqXHR.getResponseHeader('X-Subscriber-Status'));
alert("textStatus " + textStatus);
alert("errorThrown " + errorThrown);
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", …Run Code Online (Sandbox Code Playgroud) 我一直在尝试为jQuery设置自定义ajaxTransports,以便在某些情况下为我们的产品缩短某些工作流程.但是,我没有成功地使这些传输得到尊重(而我有许多工作定制ajaxPrefilters).
测试了多个版本的jQuery:
使用多个浏览器进行测试:
...
他们都没有工作.
JsFiddle测试用例: http ://jsfiddle.net/PVYut/
...
如果我添加一个dataType来缩小它,那么它工作正常.
JsFiddle测试用例: http ://jsfiddle.net/PVYut/1/
...
我只是做错了吗?我很高兴被告知,只要我能让这个工作!-_-
在IE8和9中,当我正在进行CORS webapi调用时,我收到以下JavaScript错误:
Error: Access is denied.
{
[functions]: ,
description: "Access is denied.",
message: "Access is denied.",
name: "Error",
number: -2147024891
}
Run Code Online (Sandbox Code Playgroud)
我设置了像这里描述的WebApi http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
所以WebApi包含:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
[...]
Run Code Online (Sandbox Code Playgroud)
我的测试AngularJS App:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ng="http://angularjs.org" ng-app="app">
<head>
<title>test</title>
<script src="Scripts/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="testController as vm">
{{vm.test}}
{{vm.data}}
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
app.js:
var app = angular.module('app');
app.controller('testController', function ($http) {
var vm;
vm = this; …Run Code Online (Sandbox Code Playgroud)