2015-03-19 123 views
1

我正在尝试使用php打印出一行文本到一个html文件上,但是当我运行html时,它只会打印未定义的单词。我怎样才能解决这个问题?下面是代码:你如何使用回声在PHP中打印HTML文本?

HTML:

<html> 
<head> 
</head> 
<body> 
<script type="text/javascript"> 
var xmlhttp=new XMLHttpRequest(); 
var textinhtml=document.createElement("div"); 
var text=document.createTextNode(xmlhttp.open("GET","http://mikeyrichards.bugs3.com/test.php",true)); 
textinhtml.appendChild(text); 
document.body.appendChild(textinhtml); 
xmlhttp.send(); 
</script> 
</body> 

PHP:

<?php 
echo "Hello, World" 
?> 
+0

您对XMLHttpRequest的使用是错误的,尤其是在异步模式下执行时,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest – dvhh 2015-03-19 03:12:19

+1

您确实知道php文件需要在任何可执行的php代码之前有<?php? – rivimey 2015-03-19 03:14:51

+0

我相信只有直接包含到html中才是真实的。谢谢。 – Mikey 2015-03-19 03:18:43

回答

2

正如评论你的XMLHttpRequest用法是错误的,你应该检查它的在线例子,像this example from the mozilla dev network

适应你的脚本:

<script type="text/javascript"> 
    var xmlhttp=new XMLHttpRequest(); 
    xmlhttp.onload = function() { 
     var textinhtml=document.createElement("div"); 
     var text=document.createTextNode(this.responseText); 
     textinhtml.appendChild(text); 
     document.body.appendChild(textinhtml); 
    } 
    xmlhttp.open("GET","http://mikeyrichards.bugs3.com/test.php",true) 
    xmlhttp.send(); 
</script> 

此脚本未解决请求中的错误。请阅读文档来处理它们。

+0

该代码获得了数据显示,但它也引入了服务域中的大量评论。该代码现在可以工作,但我稍后可能需要更多帮助。 – Mikey 2015-03-19 03:28:30

+0

因为我假设你想做一个跨域xhr请求,你应该阅读[cors http://www.html5rocks.com/en/tutorials/cors/]或JSONP请求 – dvhh 2015-03-19 04:22:46