1

我有一个 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 做了一些时髦的事情。我错过了什么

4

3 回答 3

1

由于您只是使用数字作为键,因此假设您需要一个数组。

于 2013-05-10T18:00:50.573 回答
1

试试这个:

echo json_encode($errors, JSON_FORCE_OBJECT);

http://www.php.net/manual/en/json.constants.php

此外,您的 PHP 脚本应包含:

header("Content-Type: application/json");

在任何echo陈述之前。

于 2013-05-10T18:01:53.120 回答
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);
于 2013-05-10T18:20:19.510 回答