0

I'm having a problem like many other people, being able to read a PHP array variable after having sent it through ajax() post. Ajax is succeeding and displaying the returned data, which is NULL. I have already thoroughly researched SO solutions for this JSON/PHP problem, and my problem description shows 'almost' EVERY solution on SO so far.

On the PHP side I've tried:

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

(Skipping over $HTTP_RAW_POST_DATA (deprecated) because it's equal to file_get_contents('php://input')

and also:

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

I've already tried clearing the UTF-8 BOM with the sed command

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

My .ajax() looks like this:

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

On the Javascript side here is my array:

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

I've checked to make sure there is no JSON formatting error, the following successfully shows me a valid JSON formatted array:

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

1 回答 1

1

You need to change to:

data: JSON.stringify(arr),

When you give an object to the data: option, it converts it to URL-encoded format, not JSON.

Or you can leave the data: option as it is, but get rid of the contentType: option, and then you should use

$data = json_decode($_POST['a_arr'], true);
于 2019-05-17T20:00:00.670 回答