Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - ajax: responsetext returns my entire php code locally

I found a good Tutorial: tutorial

but it doesn't work locally. The Problem is, that the responsetext returns my entire php code. I double-click at my ajaxclock.html and use Firefox. Surprisingly, it works on the server.

Here the code: ajaxclock.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>AJAX Tutorial</title>
</head>
<body>
    <div id="time"></div>
    <button onclick="getTime();">Aktualisieren</button>
    <script type="text/javascript" src="script.js"></script>
</body>
</html> 

script.js

var req = getXmlHttpRequestObject();
window.onload = getTime();

function getXmlHttpRequestObject()
{
    if(window.XMLHttpRequest) 
    {
         return new XMLHttpRequest();
    } 
    else if(window.ActiveXObject) 
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else 
    {
        alert('Ajax funktioniert bei Ihnen nicht!');
    }
}

function getTime()
{
    if(req.readyState == 4 || req.readyState == 0) 
    {
        req.open('GET', 'ajaxclock.php', true);
        req.setRequestHeader("Content-Type","text/plain");
        req.onreadystatechange = setMessage;
        req.send(null);
    }
}

function setMessage()
{
    if(req.readyState == 4) 
    {
        var response = eval('(' + req.responseText+ ')');
        document.getElementById('time').innerHTML = response.time;
    }
}

ajaxclock.php

<?php echo '{"time": "'.date("H:i:s").'"}'; ?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Surprisingly, it works on the server.

PHP is a server side technology. It will only ever work on a server (specifically a server configured to run PHP programs).

If you use it without such a server then nothing will execute the PHP and it will be delivered to the browser in its raw state.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...