【问题标题】:How to fetch data from controller using AJAX?如何使用 AJAX 从控制器中获取数据?
【发布时间】:2021-08-20 10:20:41
【问题描述】:

我正在使用 Laravel,并在我的控制器中从外部 API 获取数据。 到目前为止,我可以成功获取数据并循环进入选择下拉菜单。

由于数据量大,我只想在用户单击特定单选按钮时获取此结果,而不是每次加载该页面时。

如何使用 AJAX 获取数据?

下面是我的代码:

结帐控制器:

public function offices(Request $request) {

  $url = Http::get('the_url_of_the_api', [
    'userName' => '123456',
    'password' => '345678',

  ]);
  $response = json_decode($url);
  $offices = $response->offices; // this is the variable I get successfully and I loop in the code bellow

}

查看

<select name="office" class="offices form-control">
  @foreach($offices as $office)
    <option value="{{ $office->name }}">{{ $office->name }}</option>
  @endforeach
</select>

现在我正在尝试使用 AJAX 获取该数据,因此我创建了一个路由和下面的 Javascript。

路线:

Route::get('/offices', 'App\Http\Controllers\CheckoutController@offices')->name('offices');

Javascript:

<script>
  $(document).ready(function(){

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

    $('input[name="radio"]').click(function(){

      $.ajax({
        type: "GET",
        url: "/offices",
        data: '',
        success: function() {
            // How can I fetch that variable offices from the controller and loop inside the select drop down box? 
        }
      });
    });

  });
</script>

【问题讨论】:

  • 您的 Route 定义建议使用 POST 请求,但您从 javascript 发送 GET 请求。由于没有任何更改,因此最好在此处使用 GET。因此路线应该是:Route::get(...)。此外,您的问题是关于 jQuery(也许还有 javascript)。不是关于 php 和 Laravel。我建议你删除这两个标签。最后是针对您的问题的建议:尝试在成功函数中获得的响应的console.log。 jQuery 文档将告诉您更多有关如何将该响应包含到函数中的信息。
  • 是的,我错过了在两个地方都改回 GET。我已经删除了 PHP 标签,但我会保留 Laravel 标签,因为这是 Laravel 主题的重要问题

标签: jquery ajax laravel


【解决方案1】:

首先我个人不会在 Laravel 中使用 Ajax,有太多更好的选择,我最喜欢的是 Laravel Livewire

使用 AJAX 的问题是你必须解决 AJAX 不能直接与 Laravel 的 Blade 模板交互的事实。我可以想到两种方法来处理这个问题。

选项 1:从您的控制器返回一个 JSON 办公室列表

让您的 CheckoutController::offices() 方法以 JSON 形式返回办公室列表 return offices;。这样,您的 ajax 方法就有了操作 dom 所需的信息。 (这未经测试,但类似这样的方法可能有效)

success: function(results) {
  let officeSelect = document.getElementsByName('office');
  let offices = results.data;
  for (var i = 0; i < offices.length; i++) {
    // BIND DATA TO <select> ELEMENT.
    officeSelect.innerHTML = officeSelect.innerHTML +
    '<option value="' + offices[i].name+ '">' + offices[i].name+ '</option>';            
  }
}

选项 2:将整个 Blade 视图返回为 html 并将其插入正确的 dom 位置。 (再次未测试)

结帐控制器


public function offices(Request $request) {

  $url = Http::get('the_url_of_the_api', [
    'userName' => '123456',
    'password' => '345678',

  ]);
  $response = json_decode($url);
  $offices = $response->offices; 
  return view('offices', compact('offices')); // This view cannot extend another view.

}

Ajax 脚本

success: function(results) {
  document.getElementsByName('office-select-wrapper').innerhtml = results.data;    
}

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多