Laravel ajax运行但没有结果

时间:2017-06-15 11:12:32

标签: ajax laravel laravel-5

我正在做一个生活搜索应该带回结果,ajax运行,它没有带来任何错误消息和我的pace.js表明它正在正确执行ajax请求(条填充到100%)它只是没有把我带回任何结果。

的Ajax:

function search_data(search_value) {
    $.ajax({
        url: '/searching/' + search_value,
        type: 'post',
        success: function(data) {
            alert(data);
            $('#results').append('<div class="alert alert-success"><div>');
            $('#results').html(data);

        },
        error: function(data) { 
            $('#results').html(data.responseText); 
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    }       
    });
}

master.blade.php(导航中的搜索框)

<form action="/searching" method="get" autocomplete="off" class="navbar-form navbar-left">
    <div class="form-group">
        <input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
    </div>
        <div id="result">

        </div>
    </div>
</form>

路线:

Route::post('/searching/{search}', 'SearchController@search');

控制器:

  public function search($search_value) {
    $search_text = $search_value;
    if ($search_text==NULL) {
        $data= Business::all();
    } else {
        $data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
        echo $data;
    }
    //$data = $data->toArray();
    return view('results')->with('results',$data)->render();
    }

//修改

上面的代码给了我一个包含所有数据的警报:

[{"id":1,"name":"dasd","type":"3","email":"fsdf@fsdf.com","logo":null,"twitter_business":null,"facebook_business":null,"instagram_business":null,"image":null,"gallery_id":null,"user_id":1,"api_key":null,"created_at":"2017-06-15 11:02:32","updated_at":"2017-06-15 11:02:32"}]<table style="width:100%"> 
<tr> 
<td></td> 
<td>dasd</td> 
</tr> 
</table>

但不附加数据或执行.html

3 个答案:

答案 0 :(得分:0)

从你的路线返回一个json响应:

$data = $data->toArray();

return response()->json(['data' => view('results')->with('results',$data)]);

您可能需要先渲染视图,最后调用render()。

return response()->json(['data' => view('results')->with('results',$data)->render()]);

答案 1 :(得分:0)

试试这个:

$form = $('#someid');// give this id to the form
$.ajax({
    type: $form.attr('method'),
    url: $form.attr('action'),
    data: $form.serialize(),
    success: function(data, status) {
        $('#results').html(data);
    },
    error: function(data, status) {   
        $('#results').html(data.responseText);
    }
});

答案 2 :(得分:0)

  

试试这个

public function search($search_value) {
    $search_text = $search_value;
    if ($search_text==NULL) {
        $data= Business::all();
    } else {
        $data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
    }

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

它将以JSON

为您提供响应

而且你不需要手动将其转换为数组,因为Laravel已经自己做了......

而且......让我知道,如果你测试它......

编辑:您始终可以在Chrome或Mozilla开发者工具中查看ajax响应(网络部分)