duanbo1659 2017-03-14 02:41
浏览 170

(Laravel)如何使用AJAX将变量返回到.blade.php视图?

When the user changes the category with the select field, I want to only show the requests with that category on the view--and to do this using an AJAX request. I want to pass the object that is being returned from the Controller to AJAX's success handler into the view (the $requests variable as seen in the code below), and for the view to update the requests shown.

The data is being returned to AJAX's success handler correctly as I can console.log the object, but it doesn't update the $requests variable.

How do I achieve this, and what am I missing here?

The view that shows the requests from the DB

@extends('layouts.app')

@section('content')

{{-- Requests --}}
<div class="container">
    <div class="row requests-row">
        <div class="col-md-12">
            <h2>New requests</h2>
            <select name="category" class="form-control category">
                <option value="" disabled selected>Choose a category...</option>
                <option value="Electronics and Computers">Electronics and Computers</option>
                <option value="Hardware">Hardware</option>
            </select>
            <hr>
            <p class="block"></p>
            @foreach ($requests as $request)
                @include('components.requests')
            @endforeach
        </div>
    </div>
</div>

@endsection

The AJAX Request

$('.category').change(function() {
    $.ajax({
        method: "GET",
        url: "/category",
        data: $(this).serialize(),
        success: function(data) {
            console.log(data);
            return data;
        },
        error: function(data){
            console.log("Error: " + data);
        },
    });
});

The controller on the backend that handles the AJAX request

public function changeCategory(Request $request)
{
    $posts = Post::where('category', $request->category)->get();
    return $posts;
}
  • 写回答

2条回答 默认 最新

  • dongzh1988 2017-03-14 02:48
    关注

    May be smth like that?

    if($request->ajax()){
        return response()->json(['ajax']);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错