最近、ajaxを使用してJsonをいじり始めました。
私はこのJavaScriptコードを持っています:
var json = {
"test": [{
"number":1,
"char":"hey",
"bool":true
}]
};
$.ajax({
url: "json.php",
type: "POST",
contentType: "application/json",
data: {json: JSON.stringify(json)},
success: function(res) {
$("#box").html(res);
}
});
数分前、このコードはまったく問題echo $json['test']['number'];
なく動作しました1
。
しかし、これはまったく機能しません。「json」インデックスは UNDEFINED であると表示されているため、機能するものを使用してみcontentType: "application/x-www-form-urlencoded",
ましたが、配列項目をまったく取得できません。
関数でtrue パラメーターを渡さないjson_decode()
と、次のエラーが表示されます。
Cannot use object of type stdClass as array
私がそれを行うと、データは取得されませんが、応答には「配列」と表示されます。
そして、それが私が反響していることです:
$json = $_POST['json'];
$json = json_decode($json, true);
echo $json['test'][0];
そして、それは私の var_dump です$json
:
array(1) {
["test"]=>
array(1) {
[0]=>
array(3) {
["number"]=>
int(1)
["char"]=>
string(3) "hey"
["bool"]=>
bool(true)
}
}
}
なぜそれをしているのですか?配列を返さずに値を取得できないのはなぜですか?