我正在与Laravel一起实现一个简单的注册表单。 失败时,它应返回 json 响应:
{"success":"false", "message":"Could not log in newly registered user"}`
这按预期工作。 如果注册和登录成功,我想返回:
{"success":"true", "message":$html}
在这种情况下,将使用视图创建$html
。 其重要部分如下:
if(Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password'))))
{
$html = View::make('welcome_new_user', array('first_name' => Input::get('first_name')));
return Response::json(array('success' => 'true', 'message' => $html));
}
else
{
return Response::json(array('success' => 'false', 'message' => 'Could not log in newly created user.'));
}
失败时,我得到预期的响应。 成功后,我得到了"success":"true"
,但空message
. 我已经在返回之前立即回显了$html
,它包含预期的 html。 为什么返回中的消息为空?
View::make()
实际上返回一个Illuminate'View'View
对象。用双引号括起来的变量之所以有效,是因为这样做隐式调用 $html->__toString()
,它会调用 render()
方法并返回由 View
对象表示的 html。
从View
获取 html 的显式方法是直接调用 render()
方法($html->render()
(。
$html
是从View::make()
返回的内容。 为了在响应中返回它,需要将其括在引号中。 工作解决方案如下:
if(Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password'))))
{
$html = View::make('welcome_new_user', array('first_name' => Input::get('first_name')));
return Response::json(array('success' => 'true', 'message' => "$html"));
}
else
{
return Response::json(array('success' => 'false', 'message' => 'Could not log in newly created user.'));
}
请注意'message' => "$html"
。