是否可以通过xmlhttprequest加载内容和变量?

时间:2017-07-04 20:40:23

标签: javascript php variables xmlhttprequest

是否可以使用xmlhttprequest从* .php-File加载内容和变量?

我有一个index.php:

<script>
function loadsite() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("divrequest").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "siterequest.php", true);
    xhttp.send();
}
$(document).ready(loadsite());

</script>

<div id="divrequest"></div>

我的siterequest.php:

<?php
    echo "some dynamic content";
    echo json_encode(array($var1,$var2,$var3));
    echo "more dynamic content";
?>

我能获得变量吗?或者我是否误解了XMLHttpRequest的功能?

编辑: 如果我使用

var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);

我将获得整个页面的代码。

1 个答案:

答案 0 :(得分:0)

XMLHttpRequest向服务器发送HTTP请求以访问所需的页面。 PHP在响应数据发送回给您之前执行,在这种情况下,它被转换为HTML。因此,您无法使用此方法使用JavaScript获取变量。这种情况发生在你甚至收到数据之前。

相关问题