当PHP脚本通过XMLHttprequest运行时,如何替换div的内容而不是追加?

时间:2014-05-01 12:26:41

标签: javascript php html xmlhttprequest

有没有办法让div替换为php echo值而不是像现在这样使用以下代码附加到div?

PHP文件(generator.php):     

header('Content-type: text/html; charset=utf-8');

function output($val)
{

echo $val.str_repeat(" ",5000);
sleep(2);

}

output('Begin... (counting to 10)');

for( $i = 0 ; $i < 10 ; $i++ )
{
    output($i+1);
}

output('End...');

?>

调用HTML文件:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

function start() {

    try {
        xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    }

    xmlhttp.onreadystatechange = refreshwait;
    xmlhttp.open('GET', './generator.php', true);
    xmlhttp.send('null');
    refresher;
    }


function refresher(){

    window.setTimeout(refreshwait,1000)

}


function refreshwait() {

    if (xmlhttp.readyState == 4){

        if(xmlhttp.status == 200){

            var code = 'Finished';
            document.getElementById('view_area').innerHTML = code;  
        }

    }else{

        var responseText = xmlhttp.responseText;
        //document.getElementById("view_area").innerHTML = responseText;


        $("#view_area").html(responseText);


    }

}

</script>

</head>
<body>
<div id="a_form">
<form id="aform">
<input name="Generate" onClick="start()" type="button" value="Generate Fresh File" />
</form>
</div>
<div id="view_area"></div>
</body>
</html>

0 个答案:

没有答案