javascript - 你如何在 php 中使用 echo 打印 html 中的文本?

标签 javascript php html ajax xmlhttprequest

我正在尝试使用 php 将一行文本打印到 html 文件中,但是当我运行 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"
?>

最佳答案

如评论中所述,您对 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>

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

关于javascript - 你如何在 php 中使用 echo 打印 html 中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29136535/

相关文章:

javascript - 在 html/javascript 中存储 session 变量

javascript - HTMLCanvasElement 上 Unresolved 方法 captureStream

jquery - HTML JQUERY 在 UL/LI 上实现向下箭头

javascript - 如何在 next.config.js 文件中组合几个插件?

javascript - 虽然第一个索引是一个数组?

javascript - 返回 jade 中的复选框值。使用node.js、express 和 Mongoose

javascript - 指向同一页面的多个链接,但其中包含不同的信息

javascript - jshint 抛出“在 'break' 之前需要一个 'case' 语句”

php - 将对象显示为 HTML 和 XML

php - 流明框架路由不起作用