2014-06-26 157 views
1

我在内容加载从view_login.php到index.php's div id="display"使用AJAX脚本内容加载到DIV用ajax

var hr=new XMLHttpRequest(); 
hr.open("GET", 'view_login.php', true); 
hr.onreadystatechange = function(){ 
    if(hr.readyState == 4 && hr.status == 200){ 
     var return_data = hr.responseText; 
     document.getElementById('display').innerHTML = return_data; 
    } 
} 
hr.send(); 

不是echo $output我只想目标的div本身。

PHP/HTML

$output = ' 
<div id="visible"> 
<form> 
<input type="text" name="name"/> 
<input type="submit" /> 
</form> 
</div>'; 

echo $output; 

是有可能只是目标的div visible和它的内容,而不是每个页面上的输出中?而不使用jQuery和简单/原始的JavaScript。

+0

你甚至懒得读整个页面? – Nicco

+0

我认为正则表达式可以工作,但我不知道如何从它开始。 – Nicco

+0

当然,如果你只想以id为'visible'的div作为目标,你应该做'document.getElementById('visible')'或者这不是一个选项?而且我也不知道在这种情况下应该使用哪种正则表达式。 – vlaz

回答

0

在普通的JavaScript中有几种方法。一种方法是将HTML追加到Document Fragment(这是一个单独的文档),然后使用querySelector来取出你想要的div。

Demo

var frag = document.createDocumentFragment(); 
var div = document.createElement('div'); // create a div to contain the HTML 
div.innerHTML = return_data; // insert HTML to the div 
frag.appendChild(div); // append the div to the document fragment 

var visibleDiv = frag.querySelector("#visible"); // find the #visible div 

// append the div to the main document 
document.getElementById('display').appendChild(visibleDiv); 

其他选项是:

  • DOMParser(通过IE9 +支持)。
  • 将它作为div附加到主文档中,但您需要确保它从视图中隐藏,然后获取div并将其删除。