簡體   English   中英

通過.ajax()發布JSON數組后,無法在PHP中讀取NULL變量

[英]Cannot read NULL variable in PHP after posting JSON array through .ajax()

我遇到了一個和許多其他人一樣的問題,在通過ajax()發布后,它能夠讀取PHP數組變量。 Ajax正在成功並顯示返回的數據,即NULL。 我已經對這個JSON / PHP問題進行了徹底的SO解決方案研究,到目前為止,我的問題描述顯示了“幾乎”所有SO解決方案。

在PHP方面,我嘗試了:

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

(跳過$ HTTP_RAW_POST_DATA(已棄用),因為它等於file_get_contents('php:// input')

並且:

$data = json_decode($_POST["a_arr"], true);

我已經嘗試使用sed命令清除UTF-8 BOM

sed '1s/^\xEF\xBB\xBF//' < index.html > index2.html

我的.ajax()看起來像這樣:

$.ajax ({
    url:"file.php",
    method:"post",
    contentType: "application/json; charset=utf-8",
    data: { a_arr : JSON.stringify(arr) },
    })
    .done(function(response){
        $("#status").html(response);
    });

在JavaScript方面,這是我的數組:

var arr = [{"name":_name, "phone":_phone, "email":_email, "repname":repname, "repnumber":repnumber, "office":office}];
ajax_post(arr);

我已檢查以確保沒有JSON格式錯誤,以下代碼成功地向我顯示了有效的JSON格式的數組:

var data_arr = JSON.stringify(arr);
document.getElementById("status").innerHTML = data_arr;

您需要更改為:

data: JSON.stringify(arr),

當您為data:選項提供對象時,它會將其轉換為URL編碼格式,而不是JSON。

或者,您可以保留data:選項,但要擺脫contentType:選項,然后應使用

$data = json_decode($_POST['a_arr'], true);

暫無
暫無

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

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