【问题标题】:Laravel append data to $cList after ajax successajax 成功后,Laravel 将数据附加到 $cList
【发布时间】:2019-01-06 12:14:45
【问题描述】:

我不知道如何将新数据从控制器附加到 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

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

【问题讨论】:

    标签: javascript php ajax laravel


    【解决方案1】:

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

    public function store(Request $request) {
        ... your store function
    
        if($store) {
            return response()->json([
                'data' => $data
            ]);
        }
        return response()->json([
            'data' => $data
        ]);
    
    }
    

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

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

    在您的成功中,您现在持有已保存的数据,并且现在需要将其附加到您的 html 中。

    【讨论】:

    • 感谢您的回复。控制器和 ajax 工作。但是是否有可能异步更改 $cList 值,还是我必须在 html 的位置附加所有数据?
    • 嗯,它是异步的,您将数据异步发布到服务器端控制器 -> 您的 laravel 控制器存储方法在那里您将 json 返回到您的 ajax 承诺并将存储的数据附加到您的 html 视图中,这一切都是在没有完整页面加载的情况下完成的,它是异步的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2016-12-17
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多