簡體   English   中英

REST API ajax無法正常工作

[英]REST API ajax not working

我正在一個學校項目上工作,在該項目中,我必須編寫一個REST API應用程序,該應用程序通過基本的POST和DELETE操作與數據庫進行交互:

這是我的Python Flask文件:

from flask import Flask, render_template, redirect, url_for, jsonify, request, Response, abort
from flask_bootstrap import Bootstrap

import dbinteraction

app = Flask(__name__)
Bootstrap(app)


@app.route('/')
def hello_world():
    return redirect(url_for('index'))


@app.route('/index')
def index():
    return render_template('index.html')


@app.route('/allrecipes')
def allrecipes():
    return render_template('allrecipes.html')


@app.route('/ingredients')
def ingredients():
    return render_template('ingredients.html')


@app.route('/api/v1.0/recipes', methods=['GET'])
def get_recipes():

    # init
    recipes = []

    # get the task list from the db
    recipes_list = dbinteraction.getRecipes()

    # prepare the task list for jsonify
    for item in recipes_list:
        recipe = prepare_for_json(item)
        recipes.append(recipe)

    # return the task data
    return jsonify({'recipes': recipes})


@app.route('/api/v1.0/ingredients', methods=['GET'])
def get_ingredients():

    # init
    ingredients = []

    # get the user_ingredients list from the db
    ingredients_list = dbinteraction.getIngredients()

    # prepare the user_ingredients list for jsonify
    for item in ingredients_list:
        ingredient = prepare_for_json_ingredient(item)
        ingredients.append(ingredient)

    # return the ingredients data
    return jsonify({'ingredients': ingredients})


@app.route('/api/v1.0/ingredients', methods=['POST'])
def insert_ingredient():
    # get the request body
    add_request = request.json

    # check whether an ingredient is present or not
    if (add_request is not None) and ('name' in add_request) and ('quantity' in add_request):
        text = add_request['name']
        quantity = add_request['quantity']

        # insert in the database
        dbinteraction.insertIngredients(text, quantity)

        return Response(status=201)

    # return an error in case of problems
    abort(403)


@app.route('/api/v1.0/ingredients/<string:ing_name>', methods=['DELETE'])
def delete_ingredient(ing_name):
    # delete the ingredient
    ingredient = dbinteraction.removeIngredient(str(ing_name))

    return Response(status=200)


def prepare_for_json(item):
    """
    Convert the recipe in a dictionary for easing the JSON creation
    """
    recipe = dict()
    recipe['name'] = item[0]
    recipe['link'] = item[1]
    recipe['difficulty'] = item[2]
    return recipe


def prepare_for_json_ingredient(item):
    """
    Convert the ingredient in a dictionary for easing the JSON creation
    """
    ingredient = dict()
    ingredient['name'] = item[0]
    ingredient['quantity'] = item[1]
    return ingredient


if __name__ == '__main__':
    app.run(debug=True)

我還對數據庫的dbinteraction函數進行了編程和測試,它們可以正常工作。 我的問題是在Ingredients.html部分。 我加載並看到了我想要的頁面,帶有刪除按鈕的成分可修改列表。 但是,當我單擊刪除時,我得到了Uncaught ReferenceError: (name of the ingredient) is not defined at HTMLAnchorElement.onclick

這是我的html和javascript文件:

{% extends "bootstrap/base.html" %}
{% block title %}All recipes page{% endblock %}

{% block styles %}
{{super()}}
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.12/css/all.css"
          integrity="sha384-G0fIWCsCzJIMAVNQPfjH08cyYaUtMwjJwqiRKxxE/rx96Uroj1BtIQ6MLJuheaO9" crossorigin="anonymous">
{% endblock %}

{% block scripts %}
{{ super() }}
    <script src="{{ url_for('static', filename='kima2js.js') }}"></script>
{% endblock %}

{% block content %}
  <div class="container" style="text-align: center">
      <h1><i class="fas fa-utensils" style=""></i><br>
          Insert an ingredient:
      </h1>

      <div id="ingredients_list" class="form-inline"></div>

      <div id="insertingredient">
        <form id="addForm"class="form-inline" method="POST">
            <div class="form-group">
                <label for="ingredientName">Ingredient:</label>
                <input type="text" id="ingredientName" class="form-control" name="name"/>
            </div>
            <div class="form-group">
                <label for="ingredientQuantity">Quantity:</label>
                <input type="text" id="ingredientQuantity" class="form-control" name="quantity"/>
            </div>
            <button type="submit" class="btn-sm">Add</button>
        </form>
      </div>
  </div>

{% endblock %}

... javascript:

function addIngredient() {

    $("#ingredients_list ul").empty();
    $("#ingredientName").val('');
    $("#ingredientQuantity").val('');

    getIngredients();

}

function getIngredients() {

    $.getJSON("http://127.0.0.1:5000/api/v1.0/ingredients", function(data){
        var ingredients = data["ingredients"];
        var len = ingredients.length;
        for(var i = 0 ; i<len ; i++) {
            var t = ingredients[i];
            $("#ingredients_list ul").append("<li class='list-group-item list-group-item-text'>"+t.name+" "+t.quantity
                +"  <a class='delete btn btn-default' onclick='deleteIngredient("+ t.name +")'>" +
                " <span class='glyphicon glyphicon glyphicon-remove'></span>Delete</a></li>");
        }
    });

}

function deleteIngredient(ing_name) {

    $.ajax("/api/v1.0/ingredients/"+ing_name,
        {
            method: 'DELETE',
            success: function (status) {
                // update the list of printed ingredients: called when the DELETE is complete
                getIngredients();
            }
        }
    );

}

$(document).ready(function () {

    $("#ingredients_list").append("<ul></ul>");

    $("#ingredients_list ul").empty();

    getIngredients();

    $("#addForm").submit( function(){
        var name = $("#ingredientName").val();
        var quantity = $("#ingredientQuantity").val();
        var ingredient = {'name': name, 'quantity': quantity};
        var json = JSON.stringify(ingredient);

        $.post({
            "url": "http://127.0.0.1:5000/api/v1.0/ingredients",
            "data": json,
            "contentType":"application/json",
            "success": addIngredient
        });

        return false;
    });

});

我看不到我在做什么錯。 我唯一的猜測是onclick部分。 因為我已經在之前的實驗中單獨測試過所有其他代碼

您只需將ing_name的值寫為onclick的參數時確保ing_name的值用引號引起來即可,如下所示:

        $("#ingredients_list ul").append("<li class='list-group-item list-group-item-text'>"+t.name+" "+t.quantity
            +"  <a class='delete btn btn-default' onclick='deleteIngredient(\""+ t.name +"\")'>" +
            " <span class='glyphicon glyphicon glyphicon-remove'></span>Delete</a></li>");

否則,javascript會認為ing_name是變量名(並且未定義變量)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM