如何使用ajax post将JSON数据传递给php

3
这是代码:(#debug div文本如下所示)
$("#debug").text(JSON.stringify(data));
// Try to save to a file
$.ajax({
    type: 'POST',
    url: './json.php',
    dataType: 'json',
    data: JSON.stringify(data),            
    success: function(xhr, status, errorMessage) {
        if( xhr.responseText == "Success" ) {
            alert("Success!");
        } else {
            alert("response was "+xhr.responseText);
        }
    },
    error: function(xhr, status, errorMessage) {
        $("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
    }
});

JSON.php页面是:

<?php
openlog("scriptLog.txt", LOG_PID | LOG_PERROR, LOG_LOCAL0);
   $json = $_POST['json'];
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
    syslog(LOG_DEBUG, "Received Data");

   if (json_decode($json) != null) { /* sanity check */
    $file = fopen('./data.json','w+');
     fwrite($file, json_decode($json));
     fclose($file);
   } else {
     syslog(LOG_DEBUG,"Failure");
     return "Failure, json decode is null";
   }
   closelog();
   return "Success";
?>

在日志中我得到了以下信息:

3月14日14:50:54 scriptLog.txt[21902] : 收到数据

3月14日14:50:54 scriptLog.txt[21902] : 失败

在调试div文本中我得到了以下内容:

{"1457981454959":{"id":1457981454959,"code":"1","title":"Test","date":"22/03/2016","description":"a Task"}}RESPONSE: , error: SyntaxError: JSON Parse error: Unexpected EOF

1) 我该如何检查已发布数据的结构?例如,如何在系统日志中使用“接收到的数据:”+WHAT来查看其结构。 2) JSON解析错误?我看到的大多数示例都使用stringify函数,然后使用json_decode来获取值。为什么会出现解析错误?


为什么会有一个叫做 _POST['json'] 的东西,你只是发送了一个没有键的字符串,而且似乎发送的 JSON 中甚至没有这个名称的键?此外,解析错误是因为你使用了 dataType:json,它期望从服务器获取 JSON,但实际上它只是得到了一个普通的字符串,比如 Success 等。 - adeneo
那么,我该如何将数据作为JSON字符串发送?我应该如何返回响应? - John Wooten
只需发送对象 -> data:data,jQuery将把它转换为x-www-form,以便您可以通过键“_POST”使用它,并确保从服务器返回有效的JSON。 - adeneo
1
这个链接可能会对您有所帮助。 - IROEGBU
1个回答

1

1)我如何检查发布的数据?即在系统日志中,“接收到的数据:”+WHAT,以查看其结构。

我理解您正在调试代码,因此系统日志可能不是最好的选择。我建议使用浏览器网络控制台查看请求内容,并使用类似以下简单PHP文件来查看$_POST内容:

<?php
   echo json_encode($_POST);

在更复杂的情况下 - 使用实际的 调试器

2)JSON解析错误?我看到的大多数示例都使用这个stringify函数。然后他们使用json_decode获取值。为什么会出现解析错误?

您正在尝试在 $_POST 中使用 json 键,但您没有指示jQuery添加它,因此您收到的不是您期望的内容。

您的 $ .ajax 调用存在一些问题,以下是注释版本:

$.ajax({
    type: 'POST',
    url: './json.php',
    dataType: 'json', // Note: dataType is only important for the response
                      // jQuery now expects that your server code
                      // will return json

    // here you need to add the 'json' key
    data: {'json': JSON.stringify(data)},       

    // the success method has different order of parameters      
    //success: function(xhr, status, errorMessage) {
    success: function(data, status, xhr) {
        alert("response was "+data);
    },
    error: function(xhr, status, errorMessage) {
        $("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
    }
});

现在在服务器上,您将拥有一个名为$_POST['json']的序列化字符串,您可以使用json_decode对其进行解码。
或者,您可以发送未经序列化的JSON数据:
var data = {'test': 'abc'};

$.ajax({
    type: 'POST',
    url: './json.php',
    // No 'JSON.stringify()', just send your data
    data: data,
    ...
});

在服务器上,您将拥有$_POST ['test']abc值(因此您已经将json转换为数组)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接