【问题标题】:How to access a property value inside JsonResponse Object in PHP or Laravel?如何在 PHP 或 Laravel 中访问 JsonResponse 对象内的属性值?
【发布时间】:2016-10-22 05:17:30
【问题描述】:

我正在使用 Ajax 进行 POST,而我的服务器正在获取数据。但是,我正在努力访问用户发送的值。简而言之,我如何访问“用户”(tom)的值?任何人都可以让我走上正轨。先感谢您。这是我的 JsonResponse 对象:

[2016-10-22 05:10:49] local.INFO: From Ajax: Illuminate\Http\JsonResponse Object
(
[data:protected] => {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[callback:protected] => 
[encodingOptions:protected] => 0
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
    (
        [computedCacheControl:protected] => Array
            (
                [no-cache] => 1
            )

        [cookies:protected] => Array
            (
            )

        [headerNames:protected] => Array
            (
                [cache-control] => Cache-Control
                [content-type] => Content-Type
            )

        [headers:protected] => Array
            (
                [cache-control] => Array
                    (
                        [0] => no-cache
                    )

                [content-type] => Array
                    (
                        [0] => application/json
                    )

            )

        [cacheControl:protected] => Array
            (
            )

    )

[content:protected] =>     {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] => 
)

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.1


    【解决方案1】:

    使用 Laravel 也可以使用Illuminate getData() 方法访问数据。

    $someVar->getData();
    

    https://laravel.com/api/5.3/Illuminate/Http/JsonResponse.html#method_getData

    【讨论】:

    • 简单但拯救我的生活
    【解决方案2】:

    使用 Laravel,您可以像访问常规变量一样访问 JSON 数据。在你的情况下,你需要这样的东西:

    $username = $request->get('user');
    

    【讨论】:

    【解决方案3】:

    我解决了我的问题,我将分享它以防有人需要它。 所以我获得 JsonObjec 的方式是在 Routes.php 中执行此操作:

    Route::post('/register', function(){
    if(Request::ajax()){
        Log::info('From Ajax: ' . print_r(Response::json(Request::all()), true));
        
        return var_dump(Response::json(Request::all()));
    } 
    });
    

    但我这样做是为了实际访问用户 (Tom) 的价值。

    $somevar = (Request::all());
    Log::info('From Ajax: ' . print_r($somevar["user"], true));
    

    这解决了我的问题。希望对大家有所帮助!

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2016-12-04
      • 2014-10-10
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多