【问题标题】:AJAX not sending data to script [duplicate]AJAX不向脚本发送数据[重复]
【发布时间】: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 。尝试添加它,看看它是否有效
  • &lt;button type="button"&gt; 会给你带来更少的问题
  • 我已经按照你们的建议做了,但还是不行
  • 请扩展“不工作”。检查浏览器的 Network 控制台;是 AJAX 请求发布吗?响应是什么样的?您的 JS 代码是否在 result 中获得值

标签: php json ajax


【解决方案1】:

下面一行

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

应该是

document.getElementById('comment').value;

您还想添加 return false 以防止表单在没有 ajax 的情况下提交。

onclick = "submit();return false;"

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 2015-06-26
      • 1970-01-01
      • 2015-10-28
      • 2016-03-09
      • 1970-01-01
      相关资源
      最近更新 更多