AJAX调用unload函数返回页面的内容?

时间:2017-11-10 19:22:50

标签: php ajax

这让我疯了!

我有一个简单的HTML页面,其中包含一个在加载页面时调用的JS函数。该脚本使用AJAX / PHP向数据库发出请求。在此示例中,PHP调用页面仅返回一个字符串。虽然当我打印答案的内容时,我只是得到了页面本身的内容!!! ????? (而不是PHP脚本返回的字符串)?

以下是代码:

<!DOCTYPE html>
<head>

<script>
function parseContent()
{
    var node = document.getElementById('content');

    var xhttp = new XMLHttpRequest();
    xhttp.onload = function () {
        if (this.status === 200 && this.readyState == 4) {
            console.log(xhttp.responseText);
        }
    }
    xhttp.open('POST', 'test.php', true);
    xhttp.send();
}
</script>

<html>
<body onload='parseContent();'>
<div id='container' style='margin: 0 auto; padding: 0; width: 960px;'>

<div id='content'></div>

</div><!-- container -->
</body>
</html>

PHP文件:

<?php
echo "this is a test";
?>

结果:

[Log]   <!DOCTYPE html> (connecting_to_the_server, line 12)
    <head>

    <script>
    function parseContent()
    {
        var node = document.getElementById('content');

        var xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
            if (this.status === 200 && this.readyState == 4) {
                console.log(xhttp.responseText);
            }
        }
        xhttp.open('POST', 'test.php', true);
        xhttp.send();
    }
    </script>

    <html>
    <body onload='parseContent();'>
    <div id='container' style='margin: 0 auto; padding: 0; width: 960px;'>


    <div id='content'></div>

    </div><!-- container -->
    </body>
    </html>

我做错了什么? (肯定是愚蠢的,但现在却无法看到)。

修改

这与我在.htaccess文件中使用的重定向规则有关。

RewriteRule blabla/(.*)$ page.php?url=$1

如果我遵守规则,我会得到我提到的行为。例如,如果您输入:

www.example.com/blabla/something

然后它应该重定向到www.example.com/page.php?url=something,但由于规则的编写方式,网址中的用户仍会看到原始网址(又名www.example.com/blabla/something)。

现在,如果我使用:

RewriteRule blabla/(.*)$ page.php?url=$1 [R=301,L]

例如,然后上面的页面产生了预期的结果(我确实得到了#j;这是Ajax请求响应中的测试)。虽然在这种情况下,用户现在可以看到www.example.com/page.php?url = something&#39;我更愿意避免。我不知道为什么会这样做,但我对此不太了解。

0 个答案:

没有答案