【问题标题】:Get data from MySQL for API call using AJAX in Laravel在 Laravel 中使用 AJAX 从 MySQL 获取数据以进行 API 调用
【发布时间】:2017-12-27 23:16:41
【问题描述】:

我需要从 MySQL 获取数据(配方 ID)以进行 API 调用以显示在我的视图中。我正在尝试在 Laravel 中使用 AJAX,但我不知道从哪里开始。如果有人能指出我正确的方向,那就太好了!

这是我正在使用的 API。它有一个键,但我也很困惑为什么它不包含在 URL 中,只是 ID 的参数: https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/{id}/信息

我的数据库是什么样的: The recipe ID need to concatenate with API

我的 custom.js 文件:

$(document).ready(function () {

    function recipeDatabase() {
        var $key = "**KEY**"
        var $recipeId = **need to get from database**;

        $.ajax({
            url:"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" + $recipeId +"/information?includeNutrition=true",
            type: "GET",
            async: false,
            data: {

            },
            success: function (data) {
                $(".display").html(data);
            }
        })
    }
recipeDatabase();
})

我的视图在我的 saved.blade.php 文件中:

@extends('layouts.app')

@section('content')
    <h1>Saved Recipes</h1>
    <div class="display">

    </div>
@endsection

【问题讨论】:

  • 您可以将配方注入视图并使用配方 ID 渲染 JS。您还可以对应用程序中的端点进行 AJAX 调用并获取配方 ID,然后调用此其他 API。
  • 您是一次只使用数据库中的一个 id 还是数据库表中的所有 id 来进行 api 调用?
  • @OmisakinOluwatobi 我正在尝试使用数据库中的所有 ID 来进行 api 调用。所以一旦我进入了 saved.blade 视图,它应该会显示所有的食谱

标签: mysql ajax database laravel api


【解决方案1】:

您正在接收数据并且必须连接,以便您可以使用函数手动处理它以创建一些表,例如:

function createTable(data) {
    table = '';

    for (var i = 0; i < data.data.length; i++) {
        table += "<tr>";
        table += "<td>" + data.data[i].id + "</td>";
        table += "<td>" + data.data[i].recipe_id + "</td>";
        table += "<td>" + data.data[i].created_at + "</td>";
        table += "<td>" + data.data[i].updated_at + "</td>";
        table += "</tr>";
    }
    ;
    $('.display').html(table);
};

在你成功的 ajax 调用函数中:

success: function (data) {
                createTable(data);
                if (data.data.length == 0) {
                    $('.display').html(
                        "None data found"
                    );
                }
            },

嗯,这对我有用。只需执行一些 console.log() 以查看如何调用属性,这应该可以工作。

【讨论】:

  • 如果你想显示表格,这很好。但如果我理解得很好,OP 想知道如何从他自己的服务器的 mysql 中检索一个或多个 id 并使用 id 对外部服务进行 api 调用......
【解决方案2】:

由于您尝试获取所有配方 ID,因此您必须创建一个控制器并让它将 ID 返回到视图

public function getRecipeId()
{
    $recipe_ids =  json_encode(Recipe::pluck('id')->toArray());

    return view('recipes', compact('recipe_ids'));
}

然后您可以将元素设置为隐藏该值,例如:

<input type="hidden" value="{{ $recipe_ids }}" id="recipe_ids">

然后您可以使用 jquery 检索该元素的值并将其传递给您对该 api 的 ajax 调用:

var $key = "**KEY**";
$.each(JSON.parse($('#recipe_ids').val()), function(idx, $recipeId){


    $.ajax({
            url:"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" + $recipeId +"/information?includeNutrition=true",
            type: "GET",
            async: false,
            data: {

            },
            success: function (data) {
        //you have to find ways of displaying the response properly
                $(".display").html(data);
            }
        })
    });  

另一种方法是对控制器设置ajax调用来检索id:

public function getRecipeId()
{
    $recipe_ids =  Recipe::pluck('id')->toArray();
    return response()->json($recipe_ids);
}

然后再调用你的外部 api,例如:

$.get('/yourapi/path').done(function ($recipeIds) {
    $.each(JSON.parse($recipeIds), function(idx, $recipeId){
    var $key = "**KEY**";
    $.ajax({
            url:"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" + $recipeId +"/information?includeNutrition=true",
            type: "GET",
            async: false,
            data: {

            },
            success: function (data) {
            //you have to find ways of displaying the response properly
                $(".display").html(data);
            }
        });
    });
});

最后一种方法是使用 Guzzle,您可以使用 composer 轻松安装 guzzle,如果您拥有它,那么您的 getRecipeId 控制器方法可能如下所示:

public function getRecipeId()
{
    $recipes = [];
    $client = GuzzleHttp\Client()
    Recipe::pluck('id')->each(function($recipeId, $key) use (&$recipes){
       recipes[] = $client->get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" + $recipeId +"/information?includeNutrition=true")->getBody()->getContent();
    });
    return view('saved', compact('recipes'));
}

如果这成功了,那么当您在视图中访问$recipes 时,您可以显示来自调用的数据。

PS:这些是为了演示/解释的目的,所以你可能需要一点时间。而且对于那些 ajax 调用来说,处理失败的情况会很好,在使用 Guzzle 时也是如此。

抱歉,我没有发布如何在视图中显示它的原因是 1。我不知道响应的格式,以及 2。你应该探索 laravel doc 并尝试如何渲染它。您可以使用 console.log() 和 laravel 中使用 dd() 查看调用的结果(在 js 中);

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2019-11-05
    • 2018-02-11
    • 1970-01-01
    • 2018-03-18
    相关资源
    最近更新 更多