REST API ajax不工作

2024-04-20 04:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学校的一个项目中工作,在这个项目中,我必须编写一个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函数,它们工作得很好。我的问题在于配料.html部分。我加载并看到我想要的页面,一个可修改的成分列表与删除按钮。但是当我点击delete时,我得到一个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部分。因为我在以前的实验室里测试过所有其他的代码片段


Tags: thenamedivappforreturnrequestdef
4条回答

当您将ing_name的值作为参数写入onclick时,只需确保它在引号中,如下所示:

        $("#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是一个变量名(并且变量没有定义)。你知道吗

相关问题 更多 >