Laravel json响应通过jquery检索

时间:2015-08-10 09:22:17

标签: php jquery json laravel

如何从Laravel json响应中获取特定数据。请检查下面的代码并帮助我分别获取每个数据

json响应代码。

$search_data = array();
    foreach ($searchCustomers as $searchCustomer)
    {
        $search_data[]= array(
            "firstnameletter" => ucfirst($searchCustomer->firstname),
            "lastnameletter"  => ucfirst($searchCustomer->lastname)
        );
    }
    return response()->json(['success' => true, 'search_data' => $search_data]);

如何单独获取每个数据,例如firstnameletter?

{"success":true,"search_data":[{"firstnameletter":"","lastnameletter":"Test"},{"firstnameletter":"Thomas"
,"lastnameletter":"Tesar"},{"firstnameletter":"","lastnameletter":"Test"},{"firstnameletter":"Marcel"
,"lastnameletter":"Terlinden"},{"firstnameletter":"TEMMEL","lastnameletter":"WILFRIED"},{"firstnameletter"
:"Kfz","lastnameletter":"Technik"},{"firstnameletter":"","lastnameletter":"B\u00fcttel"},{"firstnameletter"
:"Autmobil","lastnameletter":"Technik"},{"firstnameletter":"","lastnameletter":"Test"},{"firstnameletter"
:"Flori","lastnameletter":"TEST"},{"firstnameletter":"","lastnameletter":"Test"},{"firstnameletter":"Kevin"
,"lastnameletter":"Tews"},{"firstnameletter":"G\u00fcnter","lastnameletter":"Braun"},{"firstnameletter"
:"Hasan","lastnameletter":"G\u00c3\u00b6kduman"},{"firstnameletter":"Test","lastnameletter":"Tester"
}]}

下面的代码是获取回复的js

JS

    $.post('searchbox', {searchData: searchField},
    function (html) {
      //alert(html.search_data[0]);
        for (var i = 0; i < html.length; i++) {
            alert(html[i]);
        }
    };
});

1 个答案:

答案 0 :(得分:0)

使用另一个参数告诉jQuery您收到了JSON数据

$.post('searchbox', 
    {searchData: searchField},
    function (json) {
        for (var i = 0; i < json.search_data.length; i++) {
            alert(json.search_data[i].firstnameletter);
        }
    },
    'json'
);

jQuery documentation页面上的另一个例子