AJAX未将数据发送到脚本

时间:2019-03-20 04:35:39

标签: php json ajax

我在执行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>

process.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
?>

2 个答案:

答案 0 :(得分:3)

以下行

var str = document.getElementById('comment');

应该是

document.getElementById('comment').value;

您还希望添加return false作为有效措施,以防止表单不使用Ajax提交。

onclick = "submit();return false;"

答案 1 :(得分:-1)

您看到表单事件正在运行,而不是ajax调用。您可能会考虑这样做。...

<button type="submit" name="submitComment" id='submitbtn'>Save</button>
<script>
    $('#submitbtn).click(function(event){
        event.preventDefault();
        /// rest of your code here
    });
</script>
相关问题