2015-05-14 61 views
1

我在使用IE9中的jQuery.form.js时遇到问题,其中XHR返回<form>的DOM,而不是来自POST的响应。IE9中的JQuery.Form.JS XHR错误

我创建了一个jsfiddle来演示基于this(它在IE9中有效)的问题。

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
</head> 
<body> 
    <form action="http://jquery.malsup.com/form/file-echo2.php" method="post" enctype="multipart/form-data"> 
     <input type="file" name="myfile"> 
     <input type="submit" value="Submit"> 
    </form>  
    <div id="status"></div> 
    <script> 
     (function() { 
      var status = $('#status'); 
      $('form').ajaxForm({ 
       //xhrFields: {withCredentials: true}, 
       beforeSend: function() { 
        status.html("Submitting..."); 
       }, 
       success: function() { 
        status.html("Done..."); 
       }, 
       complete: function(xhr) { 
        status.html(xhr.responseText); 
       } 
      }); 
     })();  
    </script> 
</body> 

由于原来的例子在IE 9,我想我的jsfiddle应该工作,但我不能弄清楚。任何帮助深表感谢。

回答

0

经过一晚的睡眠和清醒的头脑,我现在可以回答我自己的问题!

首先,我打开调试加入:

$.fn.ajaxSubmit.debug = true; 

调试,我可以看到在控制台下面。

[jquery.form] fileAPI :false 
[jquery.form] state = loading 
[jquery.form] cannot get iframe.contentWindow document: TypeError: Permission denied 
[jquery.form] cannot get iframe.contentDocument: Error: Access is denied. 

因此,问题是由于CORS,其中来自POST请求的响应被加载到临时,但父<html>是无法访问的。

据我所知,无法在IE9中使用jquery.form.js插件执行CORS请求。

但是,如果你正在写自己的服务托管在同一台服务器上,关键是要返回响应为HTML或XML

这里(如官方documentation解释)是如何我的代码片段用C#的Web API 2做到了:

public class UploadController : ApiController 
{ 
    [HttpPost] 
    public async Task<HttpResponseMessage> UploadFile() 
    { 
     // 
     // Verify that this is an HTML Form file upload request 
     // 
     if (!Request.Content.IsMimeMultipartContent("form-data")) 
     { 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); 
     } 

     var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(); 

     // 
     // Read the file... return a string (i.e. strResp) 
     // 

     var resp = new HttpResponseMessage(HttpStatusCode.OK); 
     resp.Content = resp.Content = new StringContent(strResp, Encoding.UTF8, "text/plain"); 

     return resp; 
    } 
} 

然后在前端用户界面,该xhr.responseText现在应该是正确的,返回的字符串。使用JavaScript来解析JSON或数组中的字符串。

希望这对其他面临类似问题的人有用。

0

我有与IE11和jQuery.Form 3.51相同的问题,对于具有多个文件上传控件的窗体。从使用旧版本的jQuery.Form开始,我知道text/plain或text/html内容类型的需求,所以我已经有了这样的需求。也就是说,我打电话给

drupal_add_http_header('Content-Type', 'text/html'); 

在我的处理函数中。几年前我曾经在某处读过设置标头应该是你在处理函数中做的第一件事,所以它是函数中的第一行。无论如何,当我在调用之前添加了一些调试代码时,它开始工作!所以基本上我的解决方案是确保上述函数调用不是我函数中的第一行。不知道这是否合乎逻辑...