Ajax app works in some browers, not others

2019-04-30 09:00发布

问题:

My ajax app works fine in Firefox, but not in IE8. Specifically, the ajax functionality doesn't work.

Here's the code I'm using:

function createXMLHttpRequest()
{
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }

  if (window.ActiveXObject)
  {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }

  return null;
}

This is the error:

Object doesn't support this property or method
ajax.js
Code:0
Line : 6
Char : 5

It works perfect in Firefox.

What is the problem with my code ?

回答1:

Consider using a function such as this:

 function createXMLHttpRequest() {
  var xmlhttp = false;
  if (window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  } else if(window.ActiveXObject) {
   try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
     xmlhttp = false;
    }
   }
  }
  return xmlhttp;
 };

Which tests for the new XMLHttp plugin in ActiveX, or defaults to the old one.

Update: Try this instead:

function createXMLHttpRequest()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

function getModIndex(val) {
    var divEle = "IndexDiv" + val;
    var request = createXMLHttpRequest();

    if ( !request ) { 
    alert( request )
    return false
    }

    var callback = function( oXML ) {
    document.getElementById( divEle ).innerHTML = oXML.responseText;
    }

    request.connect(
    '../ajax/ajax-GetIndex.php',
    'POST',
    'id=' + val,
    callback
    );
}


回答2:

straight out of jQuery:

return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
                              new XMLHttpRequest();


回答3:

Can you try this code:

function createXMLHttpRequest() { 
  if (typeof XMLHttpRequest != "undefined") { 
    return new XMLHttpRequest();
  } else if (typeof ActiveXObject != "undefined") { 
    return new ActiveXObject("Microsoft.XMLHTTP"); 
  } else { 
    throw new Error("XMLHttpRequest not supported");
}


回答4:

I was having the same problem -- reloading the page seemed to eliminate the error, but visiting the page first time I got the same error as luvboy.

I think the underlying problem has something to do with IE 8 having issues with a first-time load of the XMLHttpRequest function. I gave up searching for the real reason why, but it seems that others have had similar quirks: http://www.daniweb.com/forums/thread299941.html

Dan Beam's answer seems to work well enough and it's way less code -- it checks for the ActiveXObject first, which IE seems to be more content with.



回答5:

"I'm not sure if I figured out precisely what the problem was, but I did figure out a solution. I was going to recode it in jQuery and noticed that the code i was looking at checks for ActiveX before XMLHttpRequest, so I just flipped my code to also check for ActiveX first and now it works for both IE8 and FF.

Seems like the problem is that IE8 isn't able to create a XMLHttpRequest after I reload the page (I have no idea why) so letting it create an ActiveXObject instead makes it work all the time." I Fount this answer here

It works All the time :D :D !!



回答6:

In IE8 on Vista at least, the user needs to turn off the "native XMLHTTP support" (sounds counterintuitive). To do this:

  1. Summon "Internet Options", then click the Advanced tab.
  2. Scroll down to the "Security" set of checkboxes (this could be a while), and uncheck "Enable native XMLHTTP support". You may need to also uncheck "Enable Integrated Windows Authentication" (also in the Security section) and restart IE8, per the discovery at http://community.xajax-project.org/topic/8540/access-is-denied-error-in-ie8/

You might have your web application detect if this needs to be done by looking for a JavaScript exception whose "message" property is "Access is denied" (or something of that ilk) when an attempt is made to POST to an HTTPS URL via your AJAX object.

(With Prototype, you would add an onException key-value pair to the same place as onSuccess and onFailure. It would look something like: onException:function(irrelevant_object,exc){alert(exc.message);}

The function body will be much more involved than displaying the essence of the thrown exception.)

If the relevant exception is thrown, put up a box telling the user how to turn off the XMLHTTP item in his/her copy of IE8.



回答7:

been having similar probs and have read loads of solutions that didnt work for me

When i finally figured it out I cursed microsoft even more than usual.

the following code will work in Mozilla as it decides if no value is set it uses value inbetween the option tags to send to SetContactForm, whereas IE8 sends a blank value

<select name="contact_type" id="contact_type" onChange="SetContactForm(this.value)">
<option>email</option>
<option>address</option>
</select>

to get it to working simply add a value

<select name="contact_type" id="contact_type" onChange="SetContactForm(this.value)">
<option value="email">email</option>
<option value="address">address</option>
</select>

I hope this saves some headscratching.



回答8:

You can try UpperLower case for Microsoft.XMLHTTP i.e. (Microsoft.XMLHttp) IE8 is exraordinarily Case Sensitive



回答9:

This is code (location scrubbed) that I use for getting the contents of a text file... works in IE 8 and Chrome:

var fileName = "http://www.example.com/myfile.txt";

var txtFile;

if (window.ActiveXObject)
{
    try {// code for IE8
        txtFile = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try { // code for IE6, IE5
            txtFile = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            txtFile = false;
        }
    }
}
else if (window.XMLHttpRequest)
{
    // code for IE7, Firefox, Chrome, Opera, Safari
    txtFile = new XMLHttpRequest();
}

txtFile.open("GET",fileName,false);
txtFile.send();
var txtDoc=txtFile.responseText;
// alert(txtDoc); // this will give you the text contents