【问题标题】:jQuery AJAX Post not writing JSON data to server filejQuery AJAX Post 未将 JSON 数据写入服务器文件
【发布时间】:2017-03-14 03:52:35
【问题描述】:

我是这个语言堆栈的新手...试图了解为什么服务器上的 .json 文件没有填充来自 ajax 帖子的数据。下面是两个函数。第一个是运行在浏览器上的jquery函数,另一个是运行在服务器上的jquery调用的php函数。服务器上目录的文件权限为读写,/var/www

目前有一个名为 post_Sched.json 的零长度文件,php 函数应在其中写入 json 数据。

<script>
    function theFunction() {
                   console.log("about to post to post_Sched.php")
        console.log("post_Sched_jstringed = " + post_Sched_jstringed);

        request = $.ajax({
            url: "post_Sched.php",
            type: "POST",
            data: { 'data': post_Sched_jstringed },
            //dataType: "JSON",
            success: function (response) {
                // response from php 
                $("#jresult").text(JSON.stringify(response));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
        console.log("just posted to post_Sched.php")
   }
</script>
</head>
<body>
        <h2>JSON Post Response: </h2>
        <div id="jresult"></div>
</body>
</html>

还有一个名为 post_Sched.php 的 php 文件

<?php
  $data = $_POST['data'];
  $file = fopen('post_Sched.json','w');
  fwrite($file, $data);
  fclose($file);
  echo json_encode($data);
?>

附言JSON数据的jquery函数中有一个全局变量,我可以看到正确的字符串化结果,所以我知道jsonDat是正确的:

  var post_Sched_jstringed = JSON.stringify(Sched);

开发者工具控制台显示 parsererror SyntaxError: Unexpected token

谁能解释一下这个问题以及如何解决它?
提前致谢!

【问题讨论】:

  • 希望您的 PHP 代码中没有 DOM 就绪的处理程序和 console.logs?
  • 是的,显然我做到了。我在这里对 php 进行了编辑,以显示当前状态。我还运行了此处显示的内容,但尚未运行。
  • “顺便说一句,我在 Object responseText 中看到了整个 php 函数(来自 chrome 中的开发人员工具)。”,所以它返回 php 函数就好像它是 HTML?我不知道 php,但如果我没看错,它并没有执行代码,而且我没有看到 或它是如何进行的,这是故意的吗?

标签: jquery ajax post


【解决方案1】:

替换

data: jsonDat,

data: {data: jsonDat},

来自http://api.jquery.com/jquery.ajax/

数据

类型:PlainObject 或 String 或 Array

要发送到服务器的数据。如果还不是字符串,则将其转换为查询字符串。它附加到 GET 请求的 url。请参阅 processData 选项以防止此自动处理。对象必须是键/值对。如果 value 是一个 Array,jQuery 会根据传统设置的 value 序列化多个具有相同 key 的值(如下所述)。

<?php

//echo 'Current PHP version: ' . phpinfo();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $json = $_POST['post_Sched_jstringed'];
    print_r($_POST);

    $file = fopen('post_Sched.json','w+');
    fwrite($file, json_encode($json)); // The object is automatically deserialized, so if you want it as json, it has to be serialized again
    fclose($file);

}

?>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    function theFunction() {
        console.log("about to post to post_Sched.php")

        request = $.ajax({
            url: "", // Take note the url was changed to same page, while I was working with this.
            //dataType: "json", // Removing this resolved the client-side error
            type: "post",
            data: { // I strongly recommend having data be an object with key-value pairs.
                post_Sched_jstringed: {
                    prop1: 232,
                    prop2: "asfasf"
                }
            },

            success: function (response) {
                // response from php
                console.log(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
        console.log("just posted to post_Sched.php")
    }
</script>

【讨论】:

  • 不幸的是,这并没有做到。我想我将使用不同的服务器端脚本语言 - PHP 以外的东西(可能是 python)。我处于开发阶段的早期,它会更加熟悉......
  • 我对问题进行了一些更新,以纳入问题的当前状态。当前问题状态:JSON 数据未添加到 post_Sched.json 文件中,并且在 POST 的响应中报告了解析器错误
  • 我安装了 PHP 并做了一些实验,dataType: "json" 导致客户端错误,将数据更改为具有键和值的对象,原因是它没有将任何内容保存到文件中是该对象没有在变量中序列化,它是序列化发送的,但似乎 PHP 为您反序列化了它,为了将其保存为 json,我再次对其进行了序列化。示例中的 cmets 描述了这些变化。
  • 在删除“dataType:”JSON”并使用“data:{data:post_Sched_jstringed}”后,我能够获取帖子和回复,但是返回的回复是整个 php 文件(而不是我插入的一行的响应:“echo json_encode($json);”,并且 JSON 文本文件没有在 /var/www/ 目录中更新。看来 php 文件没有运行,刚刚返回。我会将我的帖子更新为当前状态,但假设这不是正确的协议,因为它使 Q 和 A 成绩单成为移动目标。
  • 我更新了我的帖子以显示最新版本的代码,并验证了php文件具有可执行权限
猜你喜欢
  • 2017-02-22
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多