3

以下代码段在 IE7 中不起作用是否有原因?

var http = new XMLHttpRequest();
var url = 'http://my_site.com/';
var obj = createJsonParamsObj();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(JSON.stringify(obj));

从文档看来new XMLHttpRequest()应该可以工作,但有疑问,因为我无法测试它(仅在兼容模式下),所以也许我更好地使用new ActiveXObject.

4

3 回答 3

11

谷歌中的一个小搜索将为您的基本问题提供一个很好的答案

/*
   Provide the XMLHttpRequest constructor for Internet Explorer 5.x-6.x:
   Other browsers (including Internet Explorer 7.x-9.x) do not redefine
   XMLHttpRequest if it already exists.

   This example is based on findings at:
   http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest === "undefined") {
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
    catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {}
    // Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };
}

或者

/** 
 * Gets an XMLHttpRequest. For Internet Explorer 6, attempts to use MSXML 6.0,
 * then falls back to MXSML 3.0.
 * Returns null if the object could not be created. 
 * @return {XMLHttpRequest or equivalent ActiveXObject} 
 */ 
function getXHR() { 
  if (window.XMLHttpRequest) {
    // Chrome, Firefox, IE7+, Opera, Safari
    return new XMLHttpRequest(); 
  } 
  // IE6
  try { 
    // The latest stable version. It has the best security, performance, 
    // reliability, and W3C conformance. Ships with Vista, and available 
    // with other OS's via downloads and updates. 
    return new ActiveXObject('MSXML2.XMLHTTP.6.0');
  } catch (e) { 
    try { 
      // The fallback.
      return new ActiveXObject('MSXML2.XMLHTTP.3.0');
    } catch (e) { 
      alert('This browser is not AJAX enabled.'); 
      return null;
    } 
  } 
}

参考:http ://en.wikipedia.org/wiki/XMLHttpRequest和http://www.webmasterworld.com/javascript/4027629.htm

于 2013-05-28T20:26:23.243 回答
1

来自jQuery 源代码

/* Microsoft failed to properly
 * implement the XMLHttpRequest in IE7 (can't request local files),
 * so we use the ActiveXObject when it is available
 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
 * we need a fallback.
 */

所以更好地ActiveXObject在 IE7 中使用,如下所示:

new window.ActiveXObject("Microsoft.XMLHTTP")
于 2014-11-10T08:43:39.680 回答
0

Microsoft的一个示例几乎与您在代码中所做的完全一样:

var oReq = new XMLHttpRequest();
oReq.open("POST", sURL, false);
oReq.setRequestHeader("Content-Type", "text/xml");
oReq.send(sRequestBody);

从这里开始,我什至可以想到的唯一可能的故障点是支持特定application/x-www-form-urlencoded值的错误Content-Type,我非常怀疑这是一个现存的问题。

还记得包含一个 JSON 库,因为 IE7 不包含本机JSON对象。

于 2013-05-28T20:36:47.787 回答