【发布时间】:2014-08-15 19:23:06
【问题描述】:
我有一个非常简单的方法可以在表中创建一条新记录。但我只希望登录用户(Laravel / Confide)允许此操作。在不检查用户是否登录的情况下一切正常。该脚本很好地将 JSON 字符串返回给我的 jQuery Ajax 调用。
但是,一旦我添加了“if(Auth::check()”检查,我就会在结果中得到一个巨大的额外字符串(完整的 User 类!?!?!附加了 JSON 编码的数组),弄乱了我的 JSON 编码数组。这是正常行为还是我在这里遗漏了什么?
这是工作方法:
public function create()
{
//if(Auth::check()) {
//$userId = Auth::getUser()->id; // Get logged in user id
$folder = new Folder();
$folder->parent_id = Input::get('fid');
$folder->title = 'Nieuwe map';
$folder->alias = 'nieuwe-map-'.time();
//$folder->created_by = $userId;
$folder->save();
return Response::json(array('success'));
//} else {
//return Response::json(array('error'));
//}
}
这是结果:
["success"]
当我添加 Auth 检查时,我得到这个结果:
<!--
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
} -->["success"]
【问题讨论】:
-
您介意发布您的
json视图文件的内容吗?如果你只是想发送一个 json 响应,你不能只是return Response::json('json' => ['success'] )吗? gist.github.com/anonymous/01b39d781945fff6bdba -
{{ json_encode($json) }}
-
您不应该做诸如在视图中设置内容类型之类的事情。我不知道 laravel 在使用视图响应时在内部执行的整个过程,但很有可能某些后台处理会妨碍您。你最好使用
Response::json()。看看我在第一条评论中提供的代码是否适合你。 -
我之前尝试过 Response::json() 。它没有用,所以我一直在寻找其他方法,并在此过程中使用愚蠢的“解决方案”;)。使用 Response::json 有同样的问题,它工作得很好,但是当调用 Auth::check() 时,整个事情变得无用了。