好吧,我似乎無法將JSON從我的Ajax調用,用戶數據的帖子我的API,它是建立在超薄PHP解碼..Ajax + JSON解碼+ 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)沒有效果。
任何幫助非常感謝,謝謝。
我認爲這只是在JavaScript –