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

标签 php jquery ajax

这是代码:(#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) 如何查看发布的数据? IE。 “收到的数据:”+系统日志中的内容以查看其结构。 2)JSON解析错误?我看到的大多数例子都使用这个 stringify 函数。然后他们使用 json_decode 来获取值。为什么会出现解析错误?

最佳答案

1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.

据我了解,您正在调试代码,因此系统日志可能不是最好的主意。 我只需使用浏览器网络控制台来查看请求的内容,并使用像这样的简单 php 文件来查看 $_POST 的内容:

<?php
   echo json_encode($_POST);

在更复杂的情况下 - 使用实际的 debugger .

2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?

您正在尝试在 $_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,
    ...
});

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

关于php - 如何使用ajax post将JSON数据传递给php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35995849/

相关文章:

javascript - 单击按钮后无法让 javascript 重定向到另一个 html 页面

php - 使用 $_GET 获取页面信息时如何选择 2 个表

javascript - 如何在 preventDefault() 之后启用默认链接按钮

php - 如何在同一表行上使用变量来回显 foreach 数组?

jQuery 滚动条不显示

php - 如何通过 jQuery 将文件发送到 php?

javascript - Ajax 成功事件不起作用

javascript - 如何在 jQuery 中延迟 ajax 调用?

php - 如何在 DOM 和 PHP 中获取文本节点?

php - 在 CodeIgniter 中加载多个库 - PHP