我正在编写一个代码,该代码将从 textarea 获取数据并在单击按钮时通过 ajax 提交。
下一步,PHP 将在服务器上创建一个文件,并将 ajax 数据存储到文件中。
我已经尝试过 PHP 的 addslashes 函数,但它不起作用。
我已经尝试通过上述方法完成并成功提交了文本数据。但问题在于 HTML 数据。我认为这一定是一个解析问题。
HTML代码
<textarea id="textareaCode"></textarea>
<a href="javascript:void(0);" id="savebutton" onclick="makePage()"></a>
Ajax 的 Javascript 代码
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = comment;
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();
}
</script>
最后是 PHP 代码
<?php
$content = $_GET["content"];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
我没有收到任何错误信息
最佳答案
你应该用 POST 而不是 GET,就像 Teemu 说的那样:
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
这一行设置右标题。
<textarea id="textareaCode"></textarea>
<a href="javascript:void(0);" id="savebutton" onclick="makePage()">test</a>
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = JSON.stringify({ comment: comment });
xmlhttp.open("POST","makePage.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(content);
}
</script>
PHP:
<?php
$data = json_decode(file_get_contents('php://input'), true);
$content = $data['comment'];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
关于javascript - Ajax 正在提交文本,但无法提交 HTML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56537411/