Ajax+;JSON解码+;瘦PHP问题?
好的,我似乎无法从我的ajax调用中解码JSON,该调用将用户数据发布到我的api中,该api是在slim php中构建的 这是我的ajaxAjax+;JSON解码+;瘦PHP问题?,php,javascript,ajax,json,zepto,Php,Javascript,Ajax,Json,Zepto,好的,我似乎无法从我的ajax调用中解码JSON,该调用将用户数据发布到我的api中,该api是在slim php中构建的 这是我的ajax var jsonData; jsonData = [ { username: "user", password: "pass" } ]; $.ajax({ type: "POST", url: "http://localhost/api/user/auth", data: {
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?");
}
});
这是我的瘦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\u a)没有效果
非常感谢您的帮助,谢谢 试试看
$params_str = urldecode($requestBody);
parse_str($params_str, $params_arr);
$user = json_decode($params_arr['user']);
你做错了。。。您通过post发送数据,因此您应该从那里获取json字符串,而不是试图手动读取请求正文。。。差不多
$req = $app->request();
$json = json_decode($req->post('user'));
现在,如果你真的想发送一个json请求主体,那完全是另一回事,但它需要对你的js进行更改。您需要将processData
设置为false,这样它就不会试图在内部对data
值进行编码。这也意味着您必须对其进行预编码:
$.ajax({
type: "POST",
url: "http://localhost/api/user/auth",
data: JSON.stringify({user: jsonData}), // gotta strinigfy the entire hash
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("You are good!");
},
error: function(xhr, type) {
alert("Y U NO WORK?");
}
});
问题是“用户”密钥。json解码的格式不正确。我完全删除了这个,因为它是没有必要的
所以我改变了:
data: {
user: JSON.stringify(jsonData)
},
到
我还实现了@air4x-line:
$json_a = json_decode(urldecode($requestBody));
我认为这只是JavaScription中的一个对象,我担心这不起作用。urldecode已经将字符串转换回“user=[{“username”:“user”,“password”:“pass”}]”,但是json decode没有将其转换成数组或任何东西?print\u r($json\u a)仍然不返回任何内容。hmmm:/user=开始时的键挡住了路。您能否在ajax请求的数据部分再传递一个变量,并显示
$requestBody
的外观。我认为它应该是数据:JSON.stringify(jsonData)
。对象应包含key:value
对。你没有从中得到语法错误吗?是的,你是正确的,我忘了删除我答案中的括号(我现在已经做了)。在我的代码中,我实际上只使用了数据:JSON.stringify(jsonData)
$json_a = json_decode(urldecode($requestBody));