weixin_33733810 2020-03-18 21:21 采纳率: 0%
浏览 48

js obj-> json文件(ajax,php)

I currently am getting a 200 green response, however my data is still NOT being written to my json file (i.e. it is still blank)

The JavaScript:

$(function() {
    $('form#saveTemp').submit(function() {
        let savdAta = JSON.stringify($('form#saveTemp').serializeObject());
        //let tempName = savdAta.styleName;
        console.log(savdAta);
        //console.log(JSON.stringify($('form#saveTemp').serializeObject()));

        $.ajax({
          url: './php/data.php',
          type: 'POST',
          contentType: "application/json",  
          data: {
              template: savdAta
          },
          success: function(msg) {
              console.log('data sent to php file, but..');
          }               
        });

        return false;
    });
});

data in console from savdAta is in below format: i.e.

{"styleName":"","fillType":"none","fillTrans":"0"}

PHP:

<?php

header('Content-Type: application/json');

if (!isset($_POST['savdAta']) && !empty($_POST['savdAta'])) {
    $savdAta = $_POST['savdAta'];

    $jsonObject = json_encode($savdAta);
    file_put_contents('./data.json', $jsonObject);
}

Update: Now I have the below, with no errors, and yet still my .json file is blank:

<?php

if (!empty($_POST['template'])) {
    $savdAta = $_POST['template'];

    file_put_contents('./data.json', $savdAta);
}
  • 写回答

1条回答 默认 最新

  • weixin_33726318 2020-03-18 21:31
    关注

    Your POST variable is template and you're only executing if NOT set AND NOT empty, which is not what you want and would never evaluate to true anyway:

    //Not needed
    //header('Content-Type: application/json');
    
    if (!empty($_POST['template'])) {
        $savdAta = $_POST['template'];
    
        //This is already JSON
        //$jsonObject = json_encode($savdAta);
        file_put_contents('./data.json', $savdAta);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿