iT邦幫忙

3

ajax 用 append 丟 json 給後端?

我有一個文章功能
一個表單中是用以下去給 ajax

formData = new FormData($('#form')[0]);

ajax

type: "POST",
    url: "url",
    data: formData,
    enctype: "multipart/form-data",
    cache: false,
    contentType: false,
    processData: false,

用這樣的方式丟到後端去(PHP)
表單中有 file 照片上傳跟一般 input
只是我找了一個編輯器
他 output 的格式是 json 像這樣

{  
   "time":1564653497717,
   "blocks":[  
      {  
         "type":"paragraph",
         "data":{  
            "text":"serhsrehehserhesh"
         }
      }
   ],
   "version":"2.15.0"
}

於是就有一個問題
我如何將這個 json 丟到後端去?
我的做法是

formData = new FormData($('#form')[0]);
editor.save().then((outputData) => {
   console.log(JSON.stringify(outputData));
   formData.append('outputData', JSON.stringify(outputData));
});

後端接收

foreach (json_decode($_POST['outputData'], true) as $key) {
    echo $key['time']; // 抓抓看他的 time
}

但會出現 Invalid argument supplied for foreach() 錯誤,$_POST['outputData'] 在 foreach 抓不到值,等於是沒過去後端⋯⋯
把 json string 丟到 formData 其中一個 field 但不行
這⋯⋯能怎麼解呢
萬分感謝思路!

看更多先前的討論...收起先前的討論...
louischou iT邦新手 4 級 ‧ 2019-08-01 18:49:10 檢舉
append?????抱歉我總覺得哪裡怪怪的
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 18:50:45 檢舉
我好像找到問題了⋯⋯
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 18:51:09 檢舉
明明是有值的
但是因為這裡的關係

formData = new FormData($('#form')[0]);
editor.save().then((outputData) => {
console.log(JSON.stringify(outputData));
formData.append('outputData', JSON.stringify(outputData)); <--- 這段不行,這段需要在外面
});
dragonH iT邦超人 5 級 ‧ 2019-08-01 19:02:17 檢舉
有沒有傳東西



console.log



看 f12 network

都可以
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:03:02 檢舉
沒有東西,我把它移到外面然後這樣:formData.append('outputData', '1'); 就可以取道值
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:03:15 檢舉
但我目的是要 outputData 的值
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
dragonH
iT邦超人 5 級 ‧ 2019-08-01 19:00:43
最佳解答

front

<script>
  $('#btn').click(() => {
    const outputData = {
      "time": 1564653497717,
      "blocks": [
        {
          "type": "paragraph",
          "data": {
            "text": "serhsrehehserhesh"
          }
        }
      ],
      "version": "2.15.0"
    };
    const myFormData = new FormData();
    myFormData.append('outputData', JSON.stringify(outputData));

    $.ajax({
      url: 'back.php',
      type: 'post',
      data: myFormData,
      enctype: "multipart/form-data",
      cache: false,
      contentType: false,
      processData: false,
      success() {
      },
      fail() {
      }
    })
  });
</script>

back

<?php 
  if (isset($_POST['outputData'])) {
    $dataFormat = json_decode($_POST['outputData'], true);
    print($dataFormat['time']);
    // output 1564653497717
  }
?>

codepen

只需要看 main 的部分

在最外層 的 function 加上 async

然後 outputdata 那改成

outputData = await editor.save()
    .then(data => data)
    .catch(err => console.log(err));
看更多先前的回應...收起先前的回應...
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:05:50 檢舉

我要取編輯器的值,他是這樣獲取

editor.save().then((outputData) => {
    console.log(JSON.stringify(outputData));
  });

但我原本做法不行

formData = new FormData($('#form')[0]);
editor.save().then((outputData) => {
    console.log(JSON.stringify(outputData));
    formData.append('outputData', JSON.stringify(outputData)); // 這段不行,這段需要在外面
});

於是我試試看這樣

formData = new FormData($('#form')[0]);
editor.save().then((outputData) => {
    console.log(JSON.stringify(outputData));
});
formData.append('outputData', '1');

這樣確實後端就可以取 1
表示真的不能在裡面⋯⋯
也就是說我要把 outputData 拿出來用
但我稍微試了一下全域用法

var haha;
editor.save().then((outputData) => {
    console.log(JSON.stringify(outputData));
    haha = '123';
});
console.log(haha);

得到 undefined⋯⋯

dragonH iT邦超人 5 級 ‧ 2019-08-01 19:10:44 檢舉

因為他是回傳 promise

所以不能這樣做

我補個 codepen 範例

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:11:57 檢舉

應該是 Promise 的關係⋯⋯

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:12:20 檢舉

嗯我剛看了一下確實是 Promise 異步

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:17:36 檢舉

果真需要用 await

dragonH iT邦超人 5 級 ‧ 2019-08-01 19:19:15 檢舉

有 .then .catch .finally

87% 是 promise

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:22:40 檢舉

有辦法在裡面用 function callback 嗎

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:29:57 檢舉

.then(data => data) 這一段是什麼意思?

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:35:32 檢舉

變這樣可以取到值嗎?
https://imgur.com/JuOD7jm

dragonH iT邦超人 5 級 ‧ 2019-08-01 19:37:33 檢舉
.then(data => data)

等於

.then((data) => { return data })

你貼的圖

還是在傳 promise 物件阿

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:41:17 檢舉

我是在 main 把 outputData return 然後印出 main()

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:46:00 檢舉

這樣搞定了

const main = async() => {
    outputData = await editor.save();
    formData.append('outputData', JSON.stringify(outputData));
    // 執行我要的東西
  }

  main();

感謝

dragonH iT邦超人 5 級 ‧ 2019-08-01 19:46:03 檢舉

印 main 沒有意義呀 /images/emoticon/emoticon11.gif

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:47:10 檢舉

我上面這做法是你原本希望的做法嗎?

dragonH iT邦超人 5 級 ‧ 2019-08-01 19:47:42 檢舉

這樣就能確保你 outputData 有東西

如果沒有 error 的話

火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:48:16 檢舉

那其實是不是我在裡面執行也是可以==

editor.save().then((outputData) => {
    // 執行我要的東西
  });
dragonH iT邦超人 5 級 ‧ 2019-08-01 19:50:12 檢舉

是可以啊

但是你變成後面依賴 outputData 的

全部都要寫在這裡

用 async 的話

可以


const main = async () => {
    await func1();
    await func2();
    await func3();
}
火爆浪子 iT邦研究生 1 級 ‧ 2019-08-01 19:50:49 檢舉

了解!謝謝~~~~學到一課

我要發表回答

立即登入回答