【问题标题】:AXIOS returning an empty array on ajax requestAXIOS 在 ajax 请求上返回一个空数组
【发布时间】:2018-03-29 16:47:42
【问题描述】:

我正在尝试使用 axios 检索一个数组来执行 ajax 请求,但结果始终为空。有趣的是,同样的请求也适用于 artisan tinker

让我们看一些代码:

路由/web.php 文件

Route::get('/trocaCarros/{id}', 'VitrineController@trocaCarros')->name('trocaCarros');

Vuejs 方法:

methods: {
umaMarca() {
// alert(marca.value);
axios.get('/trocaCarros/' + marca.value).then(response => this.vitrine = response.data);
  }

VitrineController.php

public function trocaCarros(Request $request)
{
$marca = $request->id;
$umaMarcaModelo = Modelo::where('marca_id','=', $marca);
return response()->json($umaMarcaModelo);
} 

浏览器响应是:

{}

但是,当我在 Tinker 这样做时:

Psy Shell v0.8.11 (PHP 7.1.6 — cli) by Justin Hileman
$marca = 212
=> 212

那么……

$modelo = App\Modelo::where('marca_id','=', $marca)->get();

它返回 6 个结果,就像我在数据库中一样:

=> Illuminate\Database\Eloquent\Collection {#994
 all: [
   App\Modelo {#995
     id: 880011,
     descricao: "Accord",
     marca_id: "212",
     categoria_id: "1",
     ativo: 1,
     created_at: "2017-08-03 18:35:19",
     updated_at: "2017-08-03 19:41:36",
   },
   App\Modelo {#996
     id: 880012,
     descricao: "City",
     marca_id: "212",
     categoria_id: "1",
     ativo: 1,
     created_at: "2017-08-03 18:47:26",
     updated_at: "2017-08-03 18:47:26",
   },

...还有另外 4 个

有人知道我错过了什么吗?

【问题讨论】:

  • 忘记了第一个中的->get()
  • 是的,我忘了。谢谢

标签: php ajax laravel vue.js


【解决方案1】:

您必须从控制器中的 url 获取参数。 像打击一样更新你的 VitrineController.php。

public function trocaCarros($id, Request $request)
{
    $marca = $id;
    $umaMarcaModelo = Modelo::where('marca_id', $marca)->get();
    return response()->json($umaMarcaModelo);
} 

【讨论】:

  • 好的,现在我想在 DIV 上渲染结果。我知道如何使用 jQuery,但是 AXIOS 是如何处理的呢?
【解决方案2】:

在axios时,可以通过以下方式获取数据:

axios.post(url,params)
.then(function(response) {
   // response.data contains the data
}).catch(function(error) {

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2021-01-27
    • 2020-03-23
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    相关资源
    最近更新 更多