在Ajax成功之后,Laravel将数据追加到$ cList

时间:2019-01-06 12:14:46

标签: javascript php ajax laravel

我不知道如何将控制器中的新数据附加到html视图中。

我的ajax帖子(有效):

   $.ajax({
    type: 'get',
    dataType: "json",
    url:getWizardSelectionUri,
    data: ....
    success:function(data){ 
        $('#bikeliste').empty()
         .....

这是我的带有静态请求的html

 @foreach(App\Bike::all() as $cList)
    <li class="list-group-item">
        <table border="0" width="100%">
          <colgroup width="200" span="3"></colgroup>
            <td>   
                <a href="{{$cList->link}}" target="_blank">

                    <img src="{{$cList->bildlink}}" height="150" width= "auto"> 
                </a>
                <br>
            </td>
            <td>
                <h5>
                    <a href="{{$cList->link}}" target="_blank">
                        <strong>{{$cList->hersteller}} </strong>
                        {{$cList->modell}} 
                        {{$cList->modelljahr}} 
                        <br>

                    </a>
                </h5>
            </td>
            <td>
                @if ($cList->gewicht)
                    <strong>Gewicht: </strong> {{$cList->gewicht}}<br>
                @endif
                @if ($cList->laufraddurchmesser)
                    <strong>Radgröße: </strong>{{$cList->laufraddurchmesser}}<br>
                @endif


            </td>
        </table>
        <br>
    </li>
@endforeach

是否可以在不重新加载页面的情况下更改数据?

1 个答案:

答案 0 :(得分:0)

您正在将数据从ajax异步发送到Controller,因此在您的controller方法中,您只需返回一个json响应:

public function store(Request $request) {
    ... your store function

    if($store) {
        return response()->json([
            'data' => $data
        ]);
    }
    return response()->json([
        'data' => $data
    ]);

}

$data包含您保存在数据库中的内容,然后将该数据返回给ajax promise并获取数据。因此,在ajax成功函数中,您必须执行以下操作:

success:function(response){ 
    ...
    var data = response.data // holds the data
    yourhtml.append(data); // dissables this one ...

现在,您成功保存了已保存的数据,现在需要将其追加到html中。