内容类型未通过php脚本正确设置

时间:2011-10-17 20:59:51

标签: php jquery http-headers

我有以下验证后运行的php代码:

try {

    if (isset($filtered) && !isset($errors)){
        $p['email']=$filtered['email'];

        # check if email exists
        if ($user->userExists($p)){
            $msg['error'] = false;
            $msg['msg'] = 'This email address is already in our database';
        } else {
            # insert user data into database
            $user->saveUser($filtered);
            $msg['error'] = false;
            $msg['msg'] = 'Successful! Go back to our homepage.';
        }
    } else {
        # echo errors back
        foreach ($errors as $value) {
            $msg['error'] = true;
            $msg['msg'] = $value;
        }
    }

我按如下方式准备json数据:

        # header encode
        header('Content-type: application/json');
        # return json encoded data
        echo $encoded = json_encode($msg);

下面这样的直接数组工作正常。

header('Content-type: application/json');
$msg['error'] = true;
$msg['msg'] = 'Please enter an email address.';
echo $encoded = json_encode($msg);

我似乎无法弄清楚我的php逻辑有什么问题。请帮助。

1 个答案:

答案 0 :(得分:0)

我能看到的唯一区别是,在适用的版本中,您可以在之前调用header()

尝试移动

header('Content-type: application/json');

在try / catch之上。我怀疑您遇到此问题的原因是因为您在创建数组之前隐式访问数组$msg,这会引发E_NOTICE(或者可能是E_STRICT,我不记得了)并导致某些东西被写入输出缓冲区,因此标题被发送,你不能再操纵它们 - 尽管如果是这种情况我会期望它也会打破你的JSON ......

无论如何,请尝试以上操作并报告。