开发者

"Object doesn't support..." IE8 stops at declaring ordinary variable

I'm trying to make a form send its data through AJAX and cancel the event sans jQuery, just for learning native JavaScript, which can never be bad, I figured. Anyway, this code is returning the error:

"Object doesn't support this property or method"

in IE8 at the line where I declare variables s and r in the send() function. I figured the problem must actually be elsewhere? Code works in both Firefox and Chrome, returning no errors. Ideas?

// 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 subm开发者_Python百科its 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);
        });
    });
}


IE8 does not support .getElementsByClassName(). See the Ultimate GetElementsByClassName for a pure JavaScript implementation that will work in IE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜