2013-08-02 2 views
2

다음 코드를 사용하면 결과가 성공적으로 표시됩니다. 내가 대신 AJAX 요청을 사용하는 경우오류를 찾을 수 없습니까? TypeError : document.getElementById (...) is null

window.onload = setInterval(func_name, 5000); 

function func_name() { 
    var ids = document.getElementById('aa').value; 
    ids_array = ids.split(','); 
    for (var i in ids_array) { 
     if (document.getElementById('a' + ids_array[i])) { 
      document.getElementById('a' + ids_array[i]).innerHTML = ids_array[i]; 

그러나, 나는 오류가 발생합니다 : TypeError: document.getElementById(...) is null.

var xmlhttp; 
if (window.XMLHttpRequest) { 
    xmlhttp = new XMLHttpRequest(); 
} else { // code for IE6, IE5 
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     document.getElementById('a' + ids_array[i]).innerHTML = xmlhttp.response; // error is here... TypeError: document.getElementById(...) is null 
    } 
} 
xmlhttp.open("GET", "<?php echo baseurl . 'notification.php';?>?users_id=" + ids_array[i], true); 
xmlhttp.send(); 
} 
} 
} 
} 

나는, 초보자 브라우저 문제를 (코드 라인)보고 된 위치에 대한 세부 사항을 게시하지 않은

+2

에 오신 것을 환영합니다 스택 오버플로, 당신은 코딩 여부에 시작인지, 제대로 코드와 질문 다음의 형식을 더 많은 시간을 확인하시기 바랍니다.이번에는 지역 사회의 여러 구성원이 귀하를 위해 정리를 시작했습니다. – Matt

답변

2

코드에 중대한 문제가 있습니다. 첫째, 추가 }이 끝에 있습니다. 또한, window.onload = setInterval(func_name, 5000);은 다음과 같아야합니다

다음
window.onload = function() { 
    setInterval(func_name, 5000); 
} 

, for (var i in ids_array)

for(var i=0; i<ids_array.length; i++) { ... 

이 문제의 일부가 될 수 있어야한다. 몇 가지 이유로 your current loop may not work as you'd expect.

마지막으로, Ajax는 비동기식입니다. xmlhttp.onreadystatechange에 할당 된 함수는 루프가 완료된 후에 만 ​​실행되고 i 값은 배열의 마지막 값 (현재 코드에서) 또는 배열 길이 (제안 된 새 버전에서)가됩니다. 가장 짧은 수정은 다음과 같습니다

xmlhttp.onreadystatechange = (function(i) { 
    return function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById('a' + ids_array[i]).innerHTML = xmlhttp.response; // error is here... TypeError: document.getElementById(...) is null 
     } 
    } 
}(i)); 

JavaScript closure inside loops – simple practical example


에서 찾을 수 있습니다 이유에 대한 자세한 설명 내가 한 가지 더 실현 : 그런 여러 요청을 발사하기를, 여러 XMLHttpRequest의 개체가 필요합니다 . 나는이 같은 아약스 요청을 시작할 때 별도의 기능을 사용하는 것이 좋습니다 :

function func_name() { 
    var ids = document.getElementById('aa').value; 
    ids_array = ids.split(','); 
    for(var i=0; i<ids_array.length; i++) { 
     if (document.getElementById('a' + ids_array[i])) { 
      (function(i) { 
       callAjax("<?php echo baseurl . 'notification.php';?>?users_id=" + ids_array[i], function(response){ 
        document.getElementById('a' + ids_array[i]).innerHTML = response; 
       }); 
      }(i)); 
     } 
    } 
} 

function callAjax(url, callback) { 
    var xmlhttp; 
    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else { // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      callback(xmlhttp.responseText); 
     } 
    } 
    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
} 
+0

예, 답을 시도했지만 항상 PHP 배열에 마지막 값을받은 파일이 있습니다 ... – vazgen

+0

이제 다른 문제가 나타납니다. 루프 내에서 여러 요청을 실행할 수 없으며 여러 XMLHttpRequest가 필요합니다. 인스턴스. 어느 것이 나를 불러옵니다 : 전체 루프를 없애고 한 번에 모든 ID를 전달하고 필요한 모든 정보로 응답하는 단일 요청을 실행할 수 있습니까? – bfavaretto

+0

테이블이 있는데 첫 번째 열은 새 메시지 (메시지)에 대한 알림이어야하고 두 번째 열은 사용자의 전체 이름이어야합니다. 배열의 요소를 검사합니다. 사용자가 새 메시지를 받으면 알림이 나타납니다. – vazgen

0

이 코드 유형에 대한 죄송하지만, 내 생각 엔이 될 것입니다 :

var ids = document.getElementById('aa').value; 

가장 큰 원인은 사용자가 aa 인 id (id="aa")를 가진 요소가 없다는 것입니다. 코드에서 어딘가에

document = ...

: 어느 쪽이든 또는이 같은 기괴한 일을했다. 그것은 그것이 undefined이 아닌 이상한 종류의 null입니다.

+1

OP에서 언급했듯이 첫 번째 코드 블록은 ok이지만 오류는 두 번째 코드 블록'document.getElementById ('a'+ ids_array [i])에 나타납니다. innerHTML = xmlhttp.response; ' – Sirko

1

xmlhttp.onreadystatechange = function(), 에서 ids_array [i] 변수가 올바르게 정의되지 않았습니다. "i"변수가 모든 FOR 사이클 반복마다 재정의하기 때문입니다.

그래서 모든 코드가 있어야한다 :

var ids = document.getElementById('aa').value; 
var ids_array = ids.split(','); 

for (var i=0; i<ids_array.length; i++) 
{ 
    if (document.getElementById('a' + ids_array[i])) { 
    // For every iteration, create a closure that 
    // stores the "i" variable multiple times with different values in the closure. 
    // Also create an xmlhttp Object for each request. 
    var closure = function() 
    { 
     var xmlhttp; 
     if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
     } else { // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange=function() { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
      document.getElementById('a' + ids_array[i]).innerHTML = result; 
      // After this function executes, it and any closures it has will be 
      // available for garbage collection. 
     } 
     } 
     xmlhttp.open("GET", "<?php echo baseurl . 'notification.php';?>?users_id=" + ids_array[i], true); 
     xmlhttp.send(); 

     // This code ends, but xmlhttp objects wait for onreadystatechange event. 
    } 
    } 
} 

난 당신이 폐쇄에 대한 자세한 내용을하는 것이 좋습니다.

+0

'i '는 항상 ids_array.length + 1'이 될 것입니다. 다른 범위를 포함해야합니다. like in http://stackoverflow.com/a/18017646/444991 – Matt

+0

코드를 삭제 한 후 코드를 추가했습니다. xmlhttp.open ("GET", " ? users_id = "+ ids_array [i], true); xmlhttp.send(); 맞습니까? – vazgen

+0

@Matt for (ids_array의 var i)는 ids_array (즉, 0,1,2,3)의 모든 요소를 ​​반복하지만, 물론 ids_array.length 요소를 반복하여 0,1,2, 3, length –

관련 문제