我有一个ajax调用,它会触发一个返回数组的php脚本。
php:
$errors[1] = "you didn't enter name";
$errors[2] = "your email is incorrect";
$errors[3] = "You didnt enter password";
echo json_encode($errors);
javascript:
.....
datatype:'json',
success: function(result)
{
alert(result);
}
我希望看到:
{"1":"you didn't enter name","2":"your email is incorrect","3":"You didnt enter password"}
相反,我看到: [“您没有输入姓名”,“您的电子邮件不正确”,“您没有输入密码”
似乎json_encode做了一些时髦的事情。我缺少什么答案 0 :(得分:1)
由于您只使用数字作为键,因此它假设您需要一个数组。
答案 1 :(得分:1)
试试这个:
echo json_encode($errors, JSON_FORCE_OBJECT);
http://www.php.net/manual/en/json.constants.php
此外,您的PHP脚本应包含:
header("Content-Type: application/json");
在任何echo
陈述之前。
答案 2 :(得分:1)
然后设置错误,因为这种方式会因未定义的变量而失败。
$errors[1] = "you didn't enter name";
$errors[2] = "your email is incorrect";
$errors[3] = "You didnt enter password";
echo json_encode($errors);
请勿使用此阵列配置,而是使用:
$errors=array(NULL,
"you didn't enter name",
"your email is incorrect",
"You didnt enter password"
);
echo json_encode($errors, JSON_FORCE_OBJECT);