为什么 IE 10 拒绝通过 jQuery $.ajax 发送 POST 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13188500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is IE 10 Refusing to send POST data via jQuery $.ajax
提问by Emmanuel
Both in my development and production environment, IE 10 is refusing to send any POST data via a simple $.ajax call.
在我的开发和生产环境中,IE 10 拒绝通过简单的 $.ajax 调用发送任何 POST 数据。
My script looks like this:
我的脚本如下所示:
d = 'testvar=something';
$.ajax({
data: d,
success: function(h){
console.log(h);
}
});
The actual ajax request is going through, but no post data???
实际的ajax请求正在通过,但没有发布数据???
The request headers look normal:
请求标头看起来很正常:
Request POST /steps/~do HTTP/1.1
Accept */*
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/steps/
Accept-Language en-GB,en-AU;q=0.7,en;q=0.3
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host localhost:8080
Content-Length 0
DNT 1
Connection Keep-Alive
Cache-Control no-cache
But the request body is empty! (I'm using IE's network tab in their F12 dev bar to capture requests). In the PHP script, print_r($_POST);
returns an empty array.
但是请求体是空的!(我在他们的 F12 开发栏中使用 IE 的网络选项卡来捕获请求)。在 PHP 脚本中,print_r($_POST);
返回一个空数组。
This works fine in IE 7 - 9, chrome, FF and safari, but breaks in IE10?
这在 IE 7 - 9、chrome、FF 和 safari 中工作正常,但在 IE10 中中断?
I'm not sure if I've missed something, or if IE 10 is just buggy?
我不确定我是否遗漏了什么,或者 IE 10 只是有问题?
EDIT
编辑
I've set the global ajax settings as follows:
我已将全局 ajax 设置设置如下:
$.ajaxSetup({
url: ROOT+'~do', // ROOT is either http://localhost/.../~do or http(s)://www.steps.org.au/~do depending on production or development environment
type: 'POST'
});
Further Edit
进一步编辑
Using IE version 10.0.9200.16384 on Windows 8 Pro 64 bit
在 Windows 8 Pro 64 位上使用 IE 版本 10.0.9200.16384
Direct copy/paste of request headers are:
请求标头的直接复制/粘贴是:
Key Value
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-GB,en-AU;q=0.7,en;q=0.3
Cache-Control no-cache
Connection Keep-Alive
Content-Length 0
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Cookie __utma=91949528.1947702769.1348201656.1353212510.1353237955.6; __utmz=91949528.1348201656.1.1.utmcsr=localhost|utmccn=(referral)|utmcmd=referral|utmcct=/coconutoil.org.au/; __utmb=91949528.2.10.1353237955; __utmc=91949528; cartID=8b3b2b9187cfb1aeabd071d6ec86bbbb; PHPSESSID=bl57l7fp0h37au7g0em7i3uv13
DNT 1
Host www.steps.org.au
Referer https://www.steps.org.au/
Request POST /~do HTTP/1.1
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
X-Requested-With XMLHttpRequest
The Request body is emtpy.
请求正文是空的。
Reponse headers:
响应头:
Key Value
Response HTTP/1.1 200 OK
Server nginx/0.7.65
Date Sun, 18 Nov 2012 11:23:35 GMT
Content-Type text/html
Transfer-Encoding chunked
Connection close
X-Powered-By PHP/5.3.5-1ubuntu7.2ppa1~lucid
Expires Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma no-cache
Initiator
发起人
Property Value
Stage Document Processing
Element XMLHttpRequest
Action Processing
Document ID 0
Frame ID 0
Frame URL https://www.steps.org.au/Shop/Health-Products/
Page which replicates the problem (the entire site actually):
复制问题的页面(实际上是整个站点):
回答by Cruiser KID
Edited
已编辑
Still there is no fix from Microsoft for this except using
<meta http-equiv="x-ua-compatible" content="IE=9" >
by add the above meta tag, IE10 will run your javascript in IE9 compatible mode.
除了使用之外,Microsoft 仍然没有对此进行修复
<meta http-equiv="x-ua-compatible" content="IE=9" >
通过添加上述元标记,IE10 将在 IE9 兼容模式下运行您的 javascript。
Old answer.
旧答案。
i am posting the sample code for the test that i made, and you can also utilize the same code for your code.
我正在发布我所做的测试的示例代码,您也可以为您的代码使用相同的代码。
<html>
<head runat="server">
<script src="../Scripts/jquery-1.8.3.js"></script>
<script type="text/javascript">
var xmlHttp = null;
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
"Msxml2.XMLHTTP.7.0",
"Msxml2.XMLHTTP.6.0",
"Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"
);
function makePOSTRequest(url, parameters) {
if (window.XMLHttpRequest != null) {
//xmlHttp = new window.XMLHttpRequest();
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} else if (window.ActiveXObject != null) {
// Must be IE, find the right ActiveXObject.
var success = false;
for (var i = 0; i < XMLHTTPREQUEST_MS_PROGIDS.length && !success; i++) {
alert(XMLHTTPREQUEST_MS_PROGIDS[i])
try {
xmlHttp = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
success = true;
} catch (ex) { }
}
} else {
alert("Your browser does not support AJAX.");
return xmlHttp;
}
xmlHttp.onreadystatechange = alertContents;
xmlHttp.open('POST', url, true);
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
//xmlHttp.setRequestHeader('Content-type', 'application/json;');
xmlHttp.setRequestHeader('Content-Length', parameters.length);
xmlHttp.setRequestHeader('Accept', 'text/html,application/xhtml+xml')
//xmlHttp.setRequestHeader('Connection', "close");
xmlHttp.send(parameters);
}
function alertContents() {
// alert( this.status );
if (xmlHttp.readyState == 4) {
//alert( this.responseText );
if (xmlHttp.status == 200) {
var result = xmlHttp.responseText;
// document.getElementById('result').innerHTML = result;
// document.getElementById('submitbutton').disabled = false;
alert(result);
} else {
//alert( this.getAllResponseHeaders() );
alert("There was a problem with the request.");
}
}
}
</script>
</head>
<body>
<a href="javascript:makePOSTRequest('/api/jobs/GetSearchResult','jtStartIndex=0&jtPageSize=10&jtSorting=jobDescription ASC&jobDescription=')">Click me please</a>
GetJobDetail
<br/><br/>
Url: <input type="text" id="url" value="/api/jobs/GetSearchResult"/><br/>
parameters: <input type="text" id="parameters" value="jtStartIndex=0&jtPageSize=10&jtSorting=jobDescription ASC&jobDescription="/><br/>
submit : <input type="button" id="callMethod" value = "call" onclick="javascript: makePOSTRequest($('#url').val(), $('#parameters').val())"/>
</body>
</html>
回答by DeniroSA
I have the same issue. I think its a bug on ie 10 desktop version. running on windows 8 pro 64bit. it seems like the xhr.send method is not passing the data through. it works fine in all other browsers and ie 10 in metro mode or if you change to ie9 standards in desktop mode.
我有同样的问题。我认为它是 ie 10 桌面版本上的一个错误。在 Windows 8 pro 64 位上运行。似乎 xhr.send 方法没有传递数据。它在所有其他浏览器中都可以正常工作,即在 Metro 模式下为 10,或者如果您在桌面模式下更改为 ie9 标准。
回答by Oleg
Sorry, but my all attempts to reproduce your problems were without success. In other words all POSTs were withHTTP body and the Ajax requests worked correctly. So I could not reproduce the problem which you described. I made all tests on Internet Explorer 10, Windows 8 W64 RTM Enterprise with all current windows updates.
对不起,但我所有尝试重现您的问题都没有成功。换句话说,所有 POST 都带有HTTP 正文,并且 Ajax 请求工作正常。所以我无法重现您描述的问题。我在 Internet Explorer 10、Windows 8 W64 RTM Enterprise 和所有当前 Windows 更新上进行了所有测试。
If I add some item (for example the first one) to the chat on the pageyou referenced I can see that POST request the the following header will be produced:
如果我将一些项目(例如第一个)添加到您引用的页面上的聊天中,我可以看到 POST 请求将生成以下标头:
Anforderung POST /~do HTTP/1.1
Accept */*
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer https://www.steps.org.au/
Accept-Language de-DE,de;q=0.8,ru;q=0.7,en-US;q=0.5,en;q=0.3,ja;q=0.2
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)
Host www.steps.org.au
Content-Length 81
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Cookie __utmc=91949528; __utma=91949528.365135675.1353268932.1353268932.1353268932.1; __utmb=91949528.1.10.1353268932; __utmz=91949528.1353268932.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=ka4shsgkfvnvfdcath2klh9un0; cartID=4a90a72a379989f597276ca30c79c6f6
One can see that Content-Length
is 81 and it's not 0. The body is
可以看到Content-Length
是 81 而不是 0。身体是
i=1211&q=1&token=00f5e9f5768d09ae67f2016ebcb62e99a0d75345&cmd=addToCart&sideBar=1
The request will be answered with HTML fragment and the button become green.
请求将用 HTML 片段回答,按钮变为绿色。
To be exactly during adding the item to the chat it will be executed another code as you posted in your question. It will be executed the following code (lines 49-74) from shop.1352417874.js:
正是在将项目添加到聊天期间,它将在您发布问题时执行另一个代码。它将从shop.1352417874.js执行以下代码(第 49-74 行):
var n;
function inCart(i,t){
var a = $('#add'+i);
var q = t?1:$('#qty'+i).val();
setLoader(a,(t?60:0),0);
if(!t) a.addClass('loading').html('').attr('href','javascript:;');
// d = 'i='+i+'&q='+q+'&token='+TOKEN+'&cmd=addToCart&sideBar=1';
$.ajax({
data: {
i:i,
q:q,
token:TOKEN,
cmd:"addToCart",
sideBar: 1
},
success: function(h){
$('#sideCartContents').replaceWith(h);
mkButtons();
jsEnhance();
setLoader();
n=0;
if(!t) a.removeClass('loading').addClass('green').attr('href','Shop/Checkout.html').html('Checkout').parent().find('div.QTY').html('<strong>x'+q+'</strong> <span class="inC">in cart</span>');
flashCart();
}
});
}
The values of local i
and q
variables was 1211
and 1
in my test.
本地值i
和q
变量是1211
和1
在我的测试。
So I could not see any errors which you describe. So you have to debug the code in your environment where it will be reproduced. During the tests I would recommend you to use non-minimized code of jQuery. You could debug the code of jQuery.ajax to localize your problem.
所以我看不到你描述的任何错误。因此,您必须在将要复制的环境中调试代码。在测试期间,我建议您使用非最小化的 jQuery 代码。您可以调试 jQuery.ajax 的代码来定位您的问题。
Nevertheless I have some additional advice to you:
不过我还有一些额外的建议给你:
- First of all you should include
error
callback to the$.ajax
call and not onlysuccess
callback. - You should review the JavaScript code which you use. In the above code fragment for example you defined globalvariable
n
which will be property of the globalwindow
object. Introduction of such variables is very dangerous because of side effects and conflicts with other JavaScript codes which you include on the page. In some other places you set new properties of globalwindow
object indirectly. For example the code of globaldoErrors
function defined in common.1345011838.jslooks as following
- 首先,您应该包括
error
对$.ajax
呼叫的success
回调,而不仅仅是回调。 - 您应该查看您使用的 JavaScript 代码。例如,在上面的代码片段中,您定义了全局变量
n
,它将是全局window
对象的属性。引入此类变量是非常危险的,因为它会产生副作用,并且会与页面中包含的其他 JavaScript 代码发生冲突。在其他一些地方,您间接设置全局window
对象的新属性。比如common.1345011838.js中定义的全局doErrors
函数代码如下
function doErrors(e,d){
e=e.split(',');
for(i in e){
$((d?d+' ':'')+'[name="'+e[i]+'"]:visible').addClass('error');
}
errors();
}
In the above code you use i
variable without define it. So you set (or use) window.i
variable in the way. It's clear the usage of for-in
loop in case of array is not good. One could rewrite the code with equivalent code like for(var i=0,l=e.length; i<l; i++) {...}
.
在上面的代码中,您使用i
变量而不定义它。所以你window.i
以这种方式设置(或使用)变量。很明显,for-in
在数组的情况下循环的使用不好。可以用等效的代码重写代码,例如for(var i=0,l=e.length; i<l; i++) {...}
.
Moreover you start the code of common.1345011838.js
with
此外,您开始的代码common.1345011838.js
与
var w,r,i,p,t,l,c,z,e,m,b,k,u,s,CPH,TOKEN;
var z = new Array();
var ROOT;
which define many globalvariables with short names. It's very bad style. It can follow to conflicts with other modules which you included. Typically it would be enough to define the mostvariables which you need inside of some function. You could move declaration of the most variables inside of $(document).ready(function(){/*.HERE.*/});
.
它定义了许多具有短名称的全局变量。这是非常糟糕的风格。它可能会与您包含的其他模块发生冲突。通常,定义一些函数内部所需的最多变量就足够了。您可以移动$(document).ready(function(){/*.HERE.*/});
.
If you really need to define some globalvariables you could define onewhich will be like the namespace and all other variables you could define as the propertiesof the only global object. It's the standard practice. In the way one can reduce the number of possible conflicts between different modules which you use. For example you could use something like
如果你真的需要定义一些全局变量,你可以定义一个类似于命名空间的变量,而所有其他变量你可以定义为唯一全局对象的属性。这是标准做法。以这种方式可以减少您使用的不同模块之间可能发生的冲突数量。例如,您可以使用类似
MYGLOBALCHATOBJECT = {
root: "/",
z: [],
};
...
// add new property
MYGLOBALCHATOBJECT.TOKEN = "some value";
You should confider to define many function inside of context of another functions. In the way you could reduce the need to define many global variables. Just an example The above code of inCart
use n
variable defined above of inCart
function. The variable n
will be used only inside ofother global function flashCart
defined directly after inCart
. Moreover the function flashCart
will be used only inside of callback success
. So you can rewrite the code so, that you define both n
and flashCart
inside of callback success
:
您应该考虑在另一个函数的上下文中定义许多函数。通过这种方式,您可以减少定义许多全局变量的需要。只是一个例子 上面定义的函数inCart
使用n
变量的代码inCart
。该变量n
将仅在flashCart
直接在 之后定义的其他全局函数内部使用inCart
。此外,该函数flashCart
将仅在 callback 内部使用success
。因此,您可以重写代码,以便在 callbackn
和flashCart
内部都定义success
:
...
success: function (h) {
// define LOCAL variable n
var n = 0;
// define LOCAL function which can use outer variable n
function flashCart(){
if(n<3) {
setTimeout("flashCart()",120);
n=n+1;
}
$('#sideCartBox').toggleClass('highlighted');
}
$('#sideCartContents').replaceWith(h);
mkButtons();
jsEnhance();
setLoader();
if(!t) a.removeClass('loading').addClass('green').attr('href','Shop/Checkout.html').html('Checkout').parent().find('div.QTY').html('<strong>x'+q+'</strong> <span class="inC">in cart</span>');
flashCart(); // we use LOCAL function
}
I would recommend you additionally to test your code in JSHintor JSLint.
回答by www.amitpatil.me
I also faced same issue, Below changes worked for me.
我也遇到了同样的问题,以下更改对我有用。
<meta http-equiv="x-ua-compatible" content="IE=9" >
Worked for me :)
为我工作:)
回答by Brett Ryan
Facing this same issue I was not able to solve by setting <meta http-equiv="x-ua-compatible" content="IE=9">
, I have however forced this by setting the response header X-UA-Compatible
to IE9
which is the recommended way as the meta header is unrecognised in HTML5 validators.
面对同样的问题我是不是能够通过设置来解决<meta http-equiv="x-ua-compatible" content="IE=9">
,我已经但是通过设置响应头被迫在X-UA-Compatible
以IE9
这是推荐的方式为元报头在HTML5验证无法识别。
For J2EE applications this can be achieved with the following filter:
对于 J2EE 应用程序,这可以通过以下过滤器实现:
public class IECompatibilityFilter implements Filter {
private String compatibilityMode = "IE=10";
public IECompatibilityFilter() {
}
public String getCompatibilityMode() {
return compatibilityMode;
}
public void setCompatibilityMode(String compatibilityMode) {
this.compatibilityMode = compatibilityMode;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String mode = filterConfig.getInitParameter("compatibilityMode");
if (StringUtils.isNotBlank(mode)) {
this.compatibilityMode = StringUtils.trim(mode);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (!response.isCommitted() && response instanceof HttpServletResponse) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("X-UA-Compatible", compatibilityMode);
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
And registering in your web.xml
.
并在您的web.xml
.
<filter>
<filter-name>ieCompatibilityFilter</filter-name>
<filter-class>com.foobar.web.filter.IECompatibilityFilter</filter-class>
<init-param>
<param-name>compatibilityMode</param-name>
<param-value>IE=9</param-value>
</init-param>
</filter>
回答by Dog
There seems to be a Window 8 issue, making cross-domain httpsrequests. I can't confirm if it has anything to do with the validity of the cert, as the one on my cross-domain server is invalid (dev server).
似乎存在 Window 8 问题,导致跨域 https请求。我无法确认它是否与证书的有效性有关,因为我的跨域服务器上的证书无效(开发服务器)。
This link is a workaround, but who wants to bootstrap their entire application to make a GET request just for IE10+? http://jonnyreeves.co.uk/2013/making-xhr-request-to-https-domains-with-winjs/
此链接是一种解决方法,但谁想引导他们的整个应用程序以仅针对 IE10+ 发出 GET 请求? http://jonnyreeves.co.uk/2013/making-xhr-request-to-https-domains-with-winjs/
回答by Ricbermo
I had this same issue but just with a single request, a I mean I have a web app that handles many ajax requests. Check out your markup. I had the form inside a table for layout
我有同样的问题,但只有一个请求,我的意思是我有一个处理许多 ajax 请求的网络应用程序。检查您的标记。我在表格中放置了用于布局的表格
<table>
<form></form>
</table>
I just change it the other way. form > table.
我只是换个方式。表格 > 表格。
回答by Sasa
I have something similar (Problems with image upload from browsers to Amazon S3), and I have found that in my case the xhr object crashes when it is post-requesting http://some.server.comfrom https://my.local.server.com:123/foo. It crashes on xhr.open("POST", httpUrl, true) call.
我有类似的问题(从浏览器到 Amazon S3 的图像上传问题),我发现在我的情况下,xhr 对象在从https://my后请求http://some.server.com时崩溃。 local.server.com:123/foo。它在 xhr.open("POST", httpUrl, true) 调用时崩溃。
It probably is an IE10 bug (what a surprise ;) ), it is crashing both on Win7, and Win8.
它可能是一个 IE10 错误(多么令人惊讶;)),它在 Win7 和 Win8 上都崩溃了。