“对象不支持......”IE8在声明普通变量时停止

时间:2011-02-24 13:50:44

标签: javascript internet-explorer javascript-events

我正在尝试使表单通过AJAX发送其数据并取消事件sans jQuery,仅用于学习本机javascript,这永远不会坏,我想。无论如何,这段代码在IE8中返回错误“Object不支持这个属性或方法”,我在send()函数中声明了变量s和r。我认为问题实际上必须在其他地方吗?代码适用于Firefox和Chrome,不会返回任何错误。想法?

// Function to serialize form
function serialize() {
    var a = document.getElementsByTagName('input'), b = '';
    for (i = 0; i < a.length; i++) {
        b += a[i].name + '=' + a[i].value + '&';
    }
    return b.substring(0, b.length - 1);
}

// Function to execute when user submits form
function send(evt) {
    // Prevent the page from reloading
    if (evt.preventDefault) {
        evt.preventDefault();
    } else {
        evt.returnValue = false;
    }
    // Declare DOM variables for quick access
    var s = document.getElementsByClassName('skicka')[0], r = document.getElementById('return');
    // Hides the submit button and return text
    s.style.visibility = 'hidden';
    r.style.visibility = 'hidden';
    // Initialize and send data and request to login.php
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'login.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(serialize());
    // Check for return value from login.php
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.responseText == true) {
                // If response if true, reload page
                window.location.reload(true);
            } else {
                // If response is false, reset form and show response
                s.style.visibility = 'visible';
                r.style.visibility = 'visible';
                r.innerHTML = xhr.responseText;
            }
        }
    };
    return false;
}

// Declare event listeners
if (window.addEventListener) {
    window.addEventListener('load', function() {
        document.forms[0].addEventListener('submit', send, false);
    }, false);
} else {
    window.attachEvent('onload', function() {
        document.forms[0].attachEvent('onsubmit', function() {
            send(window.event);
        });
    });
}

1 个答案:

答案 0 :(得分:4)

IE8不支持.getElementsByClassName()。有关可在IE中使用的纯JavaScript实现,请参阅Ultimate GetElementsByClassName