【发布时间】:2018-03-31 11:42:21
【问题描述】:
简单来说,我尝试做一个网站,用户可以在其中制作一个元素,然后把它放在一个id为“box”的div元素中。 js脚本运行良好,可以创建p元素。
然后,我制作了一个 php 脚本,它保存“box” div 的 innerHTML,然后将其保存在 .txt 文件中。
现在,问题是,脚本返回 innerHTML 值作为原始值,在其中添加 p 元素之前。
这是我的 php 脚本:
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
我想这个问题已经很清楚了。这是如何获取当前值而不是原始值的方法。
如果有帮助,这里是完整的代码:
<html>
<head>
<script>
//The javascript function to add a "para" into a div with the id "box"
function addstuff() {
var parag = document.createElement("P"); // Create a <button> element
var t = document.createTextNode("Lorem Ipsum"); // Create a text node
parag.appendChild(t);
document.getElementById("box").appendChild(parag);
}
</script>
</head>
<body>
<!--Button to call the funtion-->
<button onclick="addstuff()">Add it</button>
<!--The form for the button to work-->
<form action="" method="post">
<!--The div to put the "para"s in. The style only adds borders-->
<div id="box" style="border: 2px solid black;">
<!--A pre-existing paragraph-->
<p>This was here before</p>
</div>
<!--The button to call the php-->
<input type="submit" name="use_button" value="Store in file" style="width:100%;" />
</form>
<!--The PHP-->
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
</body>
</html>
【问题讨论】:
-
使用 Jquery 我的朋友,会让你的生活更轻松
-
-
因为 PHP 运行在您的服务器上,所以 JS 运行在浏览器中,可能在世界各地的某个地方。它们之间没有直接联系。您通过 HTTP 在它们之间传递数据。在浏览器中修改的 DOM 不会镜像到服务器上。当您编写
$dom->loadHTMLfile("test.php");时,您正在服务器上加载一些文件,而不是您的用户(在浏览器中)刚刚编辑的 HTML。
标签: javascript php html innerhtml