首页 > 解决方案 > 使用 AJAX 发送 JS 对象不更新 PHP 脚本

问题描述

我已经构建了多个表单,这些表单从用户那里收集数据并将其编译成一个 JS 对象,即 JSON.stringify() 并通过以下 AJAX 代码作为“post_data”传递:

$(document).ready(function() {
  $('#php_post_show').click(function() {
    console.log(post_data);
    $.ajax({
      type: "POST",
      url: "http://localhost:80/php_beginner/index.php",
      data: {
        'post_data': post_data
      },
      success: function(data, textStatus, jqXHR) {
        console.log(data); //if it returns any data
        console.log(textStatus); //or alert(textStatus);
      },

      error: function(jqXHR, textStatus, errorThrown) {
        console.log("There is some error");
        console.log(errorThrown);
      }
    })
  })
});

我有以下 PHP:

<div id="if_sent">

<?php
if (isset($_POST['post_data'])) {

  //Retrieve the string, which was sent via the POST parameter "user"
  $post_data = $_POST['post_data'];

  //Decode the JSON string and convert it into a PHP associative array.
  echo $post_data;

  //var_dump the array so that we can view it's structure.
  var_dump($_POST);
}

var_dump($_POST);

echo "this works"
?>

</div>

执行时,我在控制台中获得“成功”,以及我想在控制台中显示的正确 PHP 代码的日志。问题是我的浏览器显示 PHP 没有更新。

这里发生了什么?为什么我的成功消息准确地输入了应该显示的内容,但页面没有显示正确的 PHP。

echo "this works" 有效,并且 var_dump($_POST) 返回一个空数组。为什么?

对于上下文,如果这与它有任何关系,我正在使用 XAMPP。

标签: javascriptphpjqueryajax

解决方案


推荐阅读