来自JSON的对象中的对象的数据

时间:2016-04-18 20:05:41

标签: php jquery json ajax

我想在此脚本中获取用户姓氏:

$(".extend-user").click(function() {
    var self = this;

    if($(self).data("details")===0)
    $.ajax({
        method: "POST",
        url: $(self).data("url"),
        data: {
            _token: $("#_token").val()
        },
        success: function(data) {
            var $details = $(self).closest('tr').next('tr');
            $details.find(".user-surname").append(surname from date object);


            $(self).data("details", 1);             
        }
    });
    if($(self).data("details")===1) {
        $(self).closest('tr').next('tr').find(".user-name").empty();
        $(self).data("details", 0);
    }
});

来自我的模特: 用户

class User extends Authenticatable {

protected $fillable = ["name", "password", "email", "date_id", "group_id"];
protected $hidden = ["password", "remember_token"];

public function date() {
    return $this->belongsTo(Date::class);
}

和日期:

class Date extends Model {

protected $fillable = ["firstname", "secondname", "surname", "pesel"];

public function user() {
    return $this->belongsTo(User::class);
}

和控制器:

public function postUser($id) {
    $user = User::where("id", $id)->first();
    $date = $user->date;

    return Response::json($user);
}

JSON data log

我可以从用户那里获得名称和任何内容,但我不知道如何在此脚本中获取来自$ user-> date-> surname的姓氏,我在consolei中看到它像对象中的objet一样发送。怎么得到这个值?

此致

1 个答案:

答案 0 :(得分:0)

JSON中的输出响应是:

{
 ...
 date: {
   surname: ''
 }
}

像php中的Simillar你可以在javascript中访问它们:

var surname = data.date.surname;

'date'来自@postUser函数$date = $user->date;