【问题标题】:How do you use echo in php to print text in html?如何在 php 中使用 echo 打印 html 中的文本?
【发布时间】:2015-03-19 03:03:34
【问题描述】:

我正在尝试使用 php 将一行文本打印到一个 html 文件中,但是当我运行 html 时,它只打印了 undefined 这个词。我怎样才能解决这个问题?代码如下:

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"
?>

【问题讨论】:

  • 你对XMLHttpRequest的使用是错误的,尤其是在异步模式下执行时,见developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
  • 你知道php文件在任何可执行的php代码之前需要有
  • 我相信只有直接包含在 html 中时才是正确的。谢谢。
  • 错误是javascript错误,而不是php错误
  • @dvhh 谢谢,尽管在 php 圈子中,最好不要包含尾随 ?> 除非你有更多的文字跟随。也就是说,如果你有一个只包含 php 代码的文件,你就没有终结符。这是为了避免输出中出现意外的文本——例如来自空白行的文本——这会弄乱其他东西。

标签: javascript php html ajax xmlhttprequest


【解决方案1】:

正如评论你对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>

此脚本不考虑请求中的错误。请阅读文档来处理它们。

【讨论】:

  • 该代码使数据显示出来,但它也从服务域中引入了一大堆 cmets。该代码现在可以工作,但我以后可能需要更多帮助。
  • 我假设你想做一个跨域的 xhr 请求,你应该阅读 [cors html5rocks.com/en/tutorials/cors] 或 JSONP 请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多