簡體   English   中英

使用php從ajax檢索發布的數據

[英]Retrieving posted data from ajax using php

我在從ajax調用中檢索發布的數據時遇到問題,不確定是什么問題。 下面腳本的控制台輸出顯示了ajax調用之前所期望的一切,但是該數據在連接器中不可用

   function updateOptions(data){

        console.log(data);
        console.log(data.id);
        console.log(data.action);

        var data = {id: data.id, action : data.action};

        console.log(data);

        $.ajax({

            type: 'POST',
            url: 'ajax.connector.php?action=updateOptions',
            data: JSON.stringify(data),
            cache: false,
            dataType  : "json",

            success: function(data, status) {

                if(data.status == 'success'){

                console.log('success');
                console.log(data);

                }else if(data.status == 'error'){
                    console.log('selects not updated');
                }

            },

            error: function(data){
                console.log('an error has occurred');
            },

        });

    }

因此,前4個console.log條目正確顯示了數據,成功情況下的第一個console.log正確顯示了。 第二個顯示:

Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}

連接器[更像導演]

   case 'updateOptions':
        error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
        $output = $sbb->updateOptions($_POST);
        break;

記錄此:

Running updateOptions function Array\n(\n)\n,

如果我嘗試在日志中回顯$ _POST ['action']或$ _POST ['data']或其他內容,則會得到未定義的索引。

我強迫ajax調用在php case函數正在調用的類中返回成功:

public function updateOptions($data){

        $output = array(
            'status' => 'success',
            'msg' => 'Category added successfully',
            'id' => $data['id'],
            'action' => $data['action'],
            'post' => $data,
        );

        return $output;

}

因此,ajax調用本身確實有效,只是未傳遞的數據。

不知何故,我沒有從ajax發布中獲取[或正確檢索]數據。

這里有什么問題?

您正在發布JSON,$ _ POST中填充了鍵=值對,請勿將JSON與application/x-www-form-urlencodedmultipart/form-data (這是php用於填充$_POST
要使用jQuery.ajax發送application/x-www-form-urlencoded數據,請傳遞一個對象,並將該對象作為數據參數

data: data, // removed JSON.stringify

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM