dongyouzhui1969 2013-07-11 15:35
浏览 64
已采纳

使用jQuery,Ajax和PHP将json写入文件

I'm trying to write a json file based upon a filled in Form

So I used an external Library for jquery that converts the Form into legitimate JSON. When I console.log that output I do get a valid json data returned.

So whenever I pass the data into a php using $.ajax and write the content to a file the PHP saves the file but the inside it just says "NULL"

here is my AJAX:

$(document).ready(function() {
    var json = $("#user-form").serializeJSON();
    $.ajax({
        url: "writejson.php",
        type: "POST",
        data: json,
        processData: false,
        contentType: 'application/json'
    });
})

And here is my PHP:

<?php
    $myFile = "kiosk.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh,var_export($_POST['data'], true));
    fclose($fh);
?>

and here is what the outputted file says:

NULL

I tried looking it up here first and tried numerous options but none of them seem to save the correct data. really strange.

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • doucheng8471 2013-07-11 15:58
    关注

    You could always change your json string from this

     var json = $("#user-form").serializeJSON();
    

    to this

     var json = {data: $("#user-form").serializeJSON()};
    

    That way when you try to retrieve $_POST['data'], it will actually be set because you defined it.

    EDIT: Important point by Shuyinsama - pointed out that you have to use the JSON.stringify method on JSON objects before posting them to PHP:

    In my case this is what I did:

    var jsontext = JSON.stringify($("#user-form").serializeJSON());
    
    var json = {data: jsontext};
    

    and then use the first PHP file to write it into a valid JSON file.

    And always remember you can use the json_decode(); within PHP if you ever need to do some processing on your JSON data, and json_encode();, respectively.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog