2017-06-10 11 views
0

最終的にXMLHttpRequestによってロードされるDIVがあります。この新しい読み込まれたdivには更新が必要です(存在する場合)Javascript:XMLHttpRequestによってロードされたDOM要素を更新する

if (document.getElementById('newdiv') !== null) { 
     document.getElementById('newdiv').innerHTML= xhr.responseText; 
    } 

は動作していないようです。以前のXMLHttpRequestによって挿入されたElementでこのチェックを実行すると、if (document.getElementById('newdiv') !== null)がnullを返し、応答は挿入されません。ページの読み込み時にDOMにある要素でこれを実行している場合、それは機能します。

ページ読み込み後に読み込まれた(多分)要素の値を更新するにはどうすればよいですか?

、Javascriptをのみ 編集F1のために

<body> 
    <button onclick="f1()"> 
    <input onchange="f2(this.value)"/> 
    <div id="parent"></div> 
</body>  
<script> 
function f1() { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) {    
     if (xhr.status == 200 && xhr.status < 300) 
     console.log(xhr.responseText); 
     console.log(document.getElementById('parent')); 
     if (document.getElementById('parent') !== null) { 
      document.getElementById('parent').innerHTML= xhr.responseText; 
     } 
    } 

    postvars = somestuff; 
    xhr.open("POST", "req.py", true); 
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhr.overrideMimeType("application/text"); 
    xhr.send(postvars); 
    } 



function f2(val) { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) {     
     if (xhr.status == 200 && xhr.status < 300) 
     console.log(xhr.responseText); 
     console.log(document.getElementById('newdiv')); 
     if (document.getElementById('newdiv') !== null) { 
      document.getElementById('newdiv').innerHTML= xhr.responseText; 
     } 
    }  

    } 
    postvars = val; 
    xhr.open("POST", "req.py", true); 
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhr.overrideMimeType("application/text"); 
    xhr.send(postvars); 
    }} 
</script> 

にxhr.responseTextを明確にするためには、

ようになり、F2のため

<div id="newdiv"></div> 

xhr.responseTextのようになりますjqueryの無ください

fancy text 
+0

DOMに '#newdiv'をどのように埋め込んでいますか? 'console.log(document.getElementById( 'newdiv'));'は正確に何を生成しますか? – Xufox

+0

私はXMLHttpRequestを挿入していますinnerHTML = xhr.responseText; newdivの親に –

+0

質問に使用しているコードを編集することはできますか?私はまだこれがどのように応答を挿入している '#newdiv'を生成するのか分かりません。 – Xufox

答えて

0

削除t hat!= null条件なので、すべてのリクエストに新しいデータが表示されます

+0

'!== null'を削除するのがなぜ助けになりますか?要素が存在しない場合、 'document.getElementById'はいつ' null'以外のものを返しますか? – Xufox

+0

私は、あなたは何を探しているのですか?あなたのページの読み込み時にjavascriptを使ってその関数を実行したいですか? –

+1

私はちょうどあなたが 'document.getElementById( 'newdiv')'と 'document.getElementById( 'newdiv')!== null'と条件が同じではないと、 '!== null'を削除すると助けになります。これは、それらが同等ではないことを意味します。コードは 'xhr.responseText'を使用しています。したがって、これはページの読み込みではなく、XHRコールバックの内部で行うことができます。 – Xufox

関連する問題