在Laravel中使用Ajax / jQuery从数据库中获取数据

时间:2019-06-24 02:17:04

标签: jquery ajax laravel

我想从数据库中获取数据(经度/纬度)并使用Ajax调用将其返回以在Google Map上绘制多个标记。

下面是包含ajax的javascript:

<script type='text/javascript'>

            (function(){

                var map,marker,latlng,bounds,infowin;
                /* initial locations for map */
                var _lat=5.441771999999999;
                var _lng=100.2936793;

                var id=1;

                function showMap(){
                    /* set the default initial location */
                    latlng={ lat: _lat, lng: _lng };

                    bounds = new google.maps.LatLngBounds();
                    infowin = new google.maps.InfoWindow();

                    /* invoke the map */
                    map = new google.maps.Map( document.getElementById('gmap'), {
                       center:latlng,
                       zoom: 15
                    });

                    /* show the initial marker */
                    marker = new google.maps.Marker({
                       position:latlng,
                       map: map,
                       title: 'Hello World!'
                    });
                    bounds.extend( marker.position );


                   $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        type: 'GET',
                        url: '{{route("voyager.dashboard")}}',
                        data: {id:id},
                        success: function (response){

                           $.each(response, function( i,item ){
                                /* add a marker for each location in response data */ 
                                addMarker( item.latitude, item.longitude, item.location_status );
                            });
                        },
                        error: function(){
                            alert('There was an error loading the data.');

                        }
                    });                 
                }

                /* simple function just to add a new marker */
                function addMarker(lat,lng,title){
                    marker = new google.maps.Marker({/* Cast the returned data as floats using parseFloat() */
                       position:{ lat:parseFloat( lat ), lng:parseFloat( lng ) },
                       map:map,
                       title:title
                    });

                    google.maps.event.addListener( marker, 'click', function(event){
                        infowin.setContent(this.title);
                        infowin.open(map,this);
                        infowin.setPosition(this.position);
                    }.bind( marker ));

                    bounds.extend( marker.position );
                    map.fitBounds( bounds );
                }

                document.addEventListener( 'DOMContentLoaded', showMap, false );
            }());
        </script>

在ajax设置中,当我放置“ dataType:json”时,执行了函数错误。输出为警报“加载数据时出错”。

这是我的控制器:

 public function _index(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        if( $locations ) {
            foreach( $locations as $location ) {
                $markers[]=array( 'latitude'=>$location->latitude, 'longitude'=>$location->longitude, 'location_status'=>$location->location_status );
            }
            return json_encode($markers, JSON_FORCE_OBJECT);     
        }

        return view('vendor.voyager.index');

我尝试了console.log(response),它显示了整个javascript代码。

当前未显示“ dataType:'json'”的错误“未捕获的TypeError:无法使用'in'运算符搜索'length'...”

我今天尝试过:

$.each(JSON.parse(response), function( i,item )

错误显示为“未捕获的SyntaxError:意外的令牌<在JSON中,位于JSON.parse()的位置0 ...”

这是api.php上的路由:

Route::group(['middleware' => ['api']], function () {
    Route::get('/', ['uses' => 'VoyagerController@_index',   'as' => 'voyager.dashboard']);
});

我对ajax / jQuery不熟悉。这是我第一次使用它。希望任何人都能帮助我。 预先谢谢你。

1 个答案:

答案 0 :(得分:1)

将功能更改为

public function googleMarkers(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        return response()->json($locations);
}

前往

的路线
Route::post('/', ['uses' => 'VoyagerController@googleMarkers',   'as' => 'gooogle.markers']);

因此,您的ajax调用

$.ajax({
   type: 'POST',
   url: '{{route("google.markers")}}',
   data: {id:id},