首页 > 解决方案 > 从 JQuery.post() 中恢复数据

问题描述

我正在使用 a$.post()将数据推送到php文件中。但是$_POST当我制作它时它是空var_dump的。

JS script

 $('#Notes').on("click", function (e) {
        e.preventDefault();
        let $id = $(document).getUrlParam("varname");
        let $text = $(this).attr('data');
        let $notes = prompt("Modifier la note", $text);
        console.log($text, $id, $notes);


        if ($notes !== null || $notes !== "") {
            $.post(
                '../buckets/update_note.buckets.php',
                {
                    id: $id,
                    notes: $notes,
                },
                function (data) {
                    console.log('Data Id : ',data.id);
                    console.log('Data Name : ',data.name);
                })
                .then(r =>{
                   location.replace('../buckets/update_note.buckets.php');
            })
         }

php文件中:

<?php

var_dump($_POST);
var_dump($_GET);

第一个console.logjs我展示了 3 个变量的值,但console.log在回调中向我展示了undefined。但我在网络调试器中看到:

Form Data
id: xxxx
notes: xxxx

任何想法 ?

标签: javascriptphpjquerypost

解决方案


我相信,在您的情况下,数据将是文本。你需要json_encode()在你的 php 中使用来打印复杂的对象。然后在您的 JS 中,您可以使用它JSON.parse()来恢复对象或在查询中定义application/json内容类型。POST就像是:

// php
$json = json_encode([
  'post' => $_POST,
  'get'  => $_GET
]);

// js
function (response) {
  const data = JSON.parse(response);
}

推荐阅读