好的,我似乎无法从我的 ajax 调用中解码 JSON,该调用将用户数据发布到我的 api,它内置在 slim php 中。
这是我的ajax..
var jsonData;
jsonData = [
{
username: "user",
password: "pass"
}
];
$.ajax({
type: "POST",
url: "http://localhost/api/user/auth",
data: {
user: JSON.stringify(jsonData)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("You are good!");
},
error: function(xhr, type) {
alert("Y U NO WORK?");
}
});
这是我的 SLIM PHP 代码..
$app->post('/user/auth', function () use ($app) {
try {
$requestBody = $app->request()->getBody(); //This works
//RequestBody is: user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D
$json_a = json_decode($requestBody); //This doesn't work
print_r($json_a); //Has no output?
$username = $json_a['user']['username']; //Therefore this doesn't work?
} catch(Exception $e) {
echo '{"error":{"text": "'. $e->getMessage() .'"}}';
}
});
正如您在注释中看到的,用代码编写的 requestBody 等于:
user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D
但是,我似乎无法解码它,因为 print_r($json_a) 没有效果。
非常感谢任何帮助,谢谢。