2011-02-24 14 views
1

我試圖讓表單通過AJAX發送它的數據,並取消事件sans jQuery,只是爲了學習原生JavaScript,它永遠不會是壞的, 我估計。無論如何,在我聲明send()函數中的變量s和r的行中,此代碼在IE8中返回錯誤「對象不支持此屬性或方法」。我認爲這個問題實際上必須在其他地方?代碼同時適用於Firefox和Chrome,不會返回任何錯誤。想法?「對象不支持...」IE8停止聲明普通變量

// 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); 
     }); 
    }); 
} 
+0

單字母變量名稱總是讓調試變得很痛苦。 : -/ – Spudley

+0

我會記住這一點,我認爲:) – fredrikekelund

回答

4

IE8不支持.getElementsByClassName()。請參閱Ultimate GetElementsByClassName以獲得可在IE中使用的純JavaScript實現。

+0

嘖嘖,我想念那裏的大錯...但非常感謝,解決了這個問題。 – fredrikekelund