【问题标题】:Recover data from JQuery.post()从 JQuery.post() 中恢复数据
【发布时间】:2019-10-16 10:44:41
【问题描述】:

我正在使用$.post() 将数据推送到php 文件。但是当我创建var_dump 时,$_POST 是空的。

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);

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

Form Data
id: xxxx
notes: xxxx

有什么想法吗?

【问题讨论】:

    标签: javascript php jquery post


    【解决方案1】:

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

    // php
    $json = json_encode([
      'post' => $_POST,
      'get'  => $_GET
    ]);
    
    // js
    function (response) {
      const data = JSON.parse(response);
    }
    

    【讨论】:

    • 同样的问题,我回显了 $json,结果是:'{"post":[],"get":[]}'
    【解决方案2】:

    你可以这样试试。

    JQuery 代码

    $('#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) {
                    var data=$.parseJSON(data);
                        console.log('Data Id : ',data.id);
                        console.log('Data Name : ',data.notes);
                    })
                    .then(r =>{
                       //location.replace('../buckets/update_note.buckets.php');
                })
             }
    

    PHP 代码

      echo json_encode($_POST);
    

    【讨论】:

    • 同样的问题,我的 php 页面上的 echo write [] 是空的。
    猜你喜欢
    • 2011-10-19
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2013-05-26
    相关资源
    最近更新 更多