【发布时间】:2019-03-20 04:35:38
【问题描述】:
我在执行 AJAX 时遇到问题。我似乎无法将 JSON 数据发送到 process.php。每次我检查数据是否已发送时,都没有打印出来。我可能已经阅读了数百篇关于此的帖子,但我似乎仍然无法弄清楚。我只包含了我认为重要的代码。任何帮助将不胜感激!
form.php(触发 JS)
<form action="process.php" method="post" id ="commentForm">
<textarea id="comment" name="comment"></textarea>
<button type="submit" name="submitComment" onclick = "submit(); return false;">Save</button>
</form>
footer.php(执行 AJAX)
<script>
function submit() {
var str = document.getElementById('comment').value;
var jsonString = {"comment":str};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange= function() {
if (xhttp.readyState== 4 && xhttp.status== 200) {
var result = JSON.parse(xhttp.responseText);
// execute some code with result
};
xhttp.open("POST", "includes/process.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('string=' + JSON.stringify(jsonString));
}
</script>
进程.php
<?php
if (isset($_POST['string'])) { // checks if data was sent
$str = $_POST['string'];
echo $str;
}
echo json_encode($arr); // assume array is already filled
?>
【问题讨论】:
-
阻止表单提交,这样页面不会刷新
-
document.getElementById('comment').value;你错过了添加.value。尝试添加它,看看它是否有效 -
<button type="button">会给你带来更少的问题 -
我已经按照你们的建议做了,但还是不行
-
请扩展“不工作”。检查浏览器的 Network 控制台;是 AJAX 请求发布吗?响应是什么样的?您的 JS 代码是否在
result中获得值