我正在开发一个以JSON形式返回数据的PHP Web服务。我现在正在使用jQuery / javascript文件测试Web服务。它似乎正在调用和正确接收数据,但服务器的返回值似乎有太多双引号。
PHP:
public static function getToken($username, $password)
{
$token = AuthenticationController::authenticate($username, $password);
if ($token)
{
$user = AuthenticationController::getUserFromToken($token);
if (UserController::userIsVerified($user->id))
{
$t = array('token' => $token);
return json_encode($t);
}
return json_encode(array('error' => 'This account has not been verified. Check email and click the provided link to verify the account.'));
}
return json_encode(array('error' => 'Authentication failed.'));
}
JS:
req.done(function(msg)
{
if (msg.error)
{
error = true;
message = msg.error;
}
else if (msg.message)
{
message = msg.message;
}
else if (msg.token)
{
token = msg.token;
}
else
{
error = true;
message = "An unknown error has occured.";
}
});
首先,msg
对象不会作为JSON对象返回,而是以字符串形式出现,因此我必须在其上执行$.parseJSON(msg)
。你在下面看到的,令牌变量最终写出来是“mylongtoken”(包括引号)。如果你在firebug中查看该变量,就像这样:“”mylongtoken“”。这只是默认行为,我需要删除引号吗?
答案 0 :(得分:1)
首先,要使jquery能够将响应解析为json,您必须返回适当的内容类型。 application/json
似乎合适。
为了增加安全性,您可以添加X-Content-Type-Options: nosniff
以防止被欺骗的浏览器作为普通页面阅读您的JSON,以尝试任何可能启用HTML解析和XSS的内容嗅探:
其次,如果你得到两组引号,那么你编码的东西会添加它们。 json_encode()没有:
echo json_encode(array('token' => 'tokenstring');
将输出{"token":"tokenstring"}
- 没有周围的引号。任何字符串中的任何引号都将使用反斜杠进行转义。