【问题标题】:update function failing, create & delete working更新功能失败,创建和删除工作
【发布时间】:2020-12-02 21:29:00
【问题描述】:

我可以创建、删除和显示所有内容,但更新功能不起作用并且什么也不做。当我在控制台日志中查看错误时,它指向

jquery.min.js:2 PUT http://localhost:5000/shop/9 400 (BAD REQUEST)  
send @ jquery.min.js:2  
ajax @ jquery.min.js:2  
updateServer @ index.html:133  
doUpdate @ index.html:129  
onclick @ index.html:35  
index.html:147  

我看不出哪里出错了。我错过了什么还是在更新服务器代码中?这是html代码。更新服务器的许多代码都是从 html 中的其他地方获取的,可以正常工作。

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title> View Shopping List</title>        
    </head>
    <body>
        <h1>Shop</h1>
        <div id="create-update" style="display:none">
            <h2>create-edit</h2>
            <table id="createUpdateForm">
                <tr>
                    <td>ID</td>
                    <td><input type="hidden" name="ID" id="idInput"></td>
                </tr>
                <tr>
                    <td>Dept</td>
                    <td><input type="text" name="Dept"></td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><input type="text" name="Name"></td>
                </tr>
                <tr>    
                    <td>Amount</td>
                    <td><input type="text" name="Amount"></td>
                </tr>
                <tr>
                    <td></td><td>
                        <button id="create-button" onclick="doCreate()">Create</button>     
                        <button id="update-button" onclick="doUpdate()">update</button>
                    </td>
                </tr>
            </table>
        </div>
        <div id="display">
            <h2>Shop</h2>
            <button onClick="showCreate()">Create</button>
            <table id="shopTable" class="table">
                <tr>
                    <th>ID</th><th>Dept</th><th>Name</th><th>Amount</th><th></th><th></th>
                </tr>
                
            </table>

        </div>

JS:

function showCreate() {
  document.getElementById('display').style.display = "none"
  document.getElementById('update-button').style.display = "none"
  document.getElementById('create-button').style.display = "block"
  document.getElementById('create-update').style.display = "block"

}

function showUpdate(thisElem) {
  var rowElement = thisElem.parentNode.parentNode;
  shop = readShopFromRow(rowElement)
  populateForm(shop)

  document.getElementById('display').style.display = "none"
  document.getElementById('update-button').style.display = "block"
  document.getElementById('create-button').style.display = "none"
  document.getElementById('create-update').style.display = "block"

}

function readShopFromRow(rowElement) {
  shop = {}
  shop.ID = rowElement.getAttribute("ID");
  shop.Dept = rowElement.cells[1].firstChild.textContent
  shop.Name = rowElement.cells[2].firstChild.textContent
  shop.Amount = rowElement.cells[3].firstChild.textContent

  return shop

}

function populateForm(shop) {
  var form = document.getElementById('createUpdateForm')


  form.querySelector('input[name="ID"]').value = shop.ID
  form.querySelector('input[name="ID"]').disabled = true

  form.querySelector('input[name="Dept"]').value = shop.Dept
  form.querySelector('input[name="Name"]').value = shop.Name
  form.querySelector('input[name="Amount"]').value = shop.Amount
}

function clearForm() {
  var form = document.getElementById('createUpdateForm')


  form.querySelector('input[name="ID"]').value = ''
  form.querySelector('input[name="ID"]').disabled = false

  form.querySelector('input[name="Dept"]').value = ''
  form.querySelector('input[name="Name"]').value = ''
  form.querySelector('input[name="Amount"]').value = ''
}

function doCreate() {
  console.log("in doCreate")
  shop = getShopFromForm()
  console.log(shop)
  $.ajax({
    url: "/shop",
    data: JSON.stringify(shop),
    method: "POST",
    dataType: "JSON",
    contentType: "application/json; charset=utf-8",
    success: function(result) {
      console.log(result)
      addShopToTable(shop)
      showDisplay()
      clearForm()

    },
    error: function(xhr, status, error) {
      console.log("error" + error)
    }
  })

}

function doUpdate() {
  shop = getShopFromForm()
  updateServer(shop)

}

function updateServer(shop) {
  $.ajax({
    url: "/shop/" + shop.ID,
    data: JSON.stringify(shop),
    method: "PUT",
    dataType: "JSON",
    contentType: "application/json; charset=utf-8",
    success: function(result) {
      console.log(result)
      updateTableRow(shop)
      showDisplay()
      clearForm()

    },
    error: function(xhr, status, error) {
      console.log("error" + error)
    }
  })
}

function doDelete(thisElem) {
  var tableElement = document.getElementById('shopTable');
  var rowElement = thisElem.parentNode.parentNode;
  var index = rowElement.rowIndex;
  ID = rowElement.getAttribute("id");
  $.ajax({
    url: "/shop/" + ID,
    method: "DELETE",
    dateType: "JSON",
    success: function(result) {
      tableElement.deleteRow(index);
    },
    error: function(xhr, status, error) {
      console.log(error)
    }
  })

}

function updateTableRow(shop) {
  rowElement = document.getElementById(shop.ID)
  rowElement.cells[1].firstChild.textContent = shop.Dept
  rowElement.cells[2].firstChild.textContent = shop.Name
  rowElement.cells[3].firstChild.textContent = shop.Amount
  //console.log("updating table")
}

function getShopFromForm() {
  var form = document.getElementById('createUpdateForm')

  var shop = {}
  shop.ID = form.querySelector('input[name="ID"]').value
  shop.Dept = form.querySelector('input[name="Dept"]').value
  shop.Name = form.querySelector('input[name="Name"]').value
  shop.Amount = form.querySelector('input[name="Amount"]').value
  //console.log(shop)
  return shop
}

function showDisplay() {
  document.getElementById('display').style.display = "block"
  document.getElementById('create-update').style.display = "none"

}

function populateTable() {
  //ajax getAll
  $.ajax({
    url: 'http://127.0.0.1:5000/shop',
    method: 'GET',
    datatype: 'JSON',
    success: function(results) {
      for (shop of results) {
        addShopToTable(shop)
      }
    },
    error: function(xhr, status, error) {
      console.log("error " + error + " code:" + status)
    }

  })

}

function addShopToTable(shop) {
  //console.log("working so far")
  tableElem = document.getElementById("shopTable")
  rowElem = tableElem.insertRow(-1)
  rowElem.setAttribute("ID", shop.ID)
  cell1 = rowElem.insertCell(0)
  cell1.innerHTML = shop.ID
  cell2 = rowElem.insertCell(1)
  cell2.innerHTML = shop.Dept
  cell3 = rowElem.insertCell(2)
  cell3.innerHTML = shop.Name
  cell4 = rowElem.insertCell(3)
  cell4.innerHTML = shop.Amount
  cell5 = rowElem.insertCell(4)
  cell5.innerHTML = '<button onclick="showUpdate(this)">Update</button>'
  cell6 = rowElem.insertCell(5)
  cell6.innerHTML = '<button onclick="doDelete(this)">delete</button>'
}
populateTable()

服务器 API

from flask import Flask, jsonify, request, abort,  make_response, url_for, render_template, redirect #https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates Render template takes template and returns actual values
from flask_cors import CORS
from ShoppingDAO import ShoppingDAO
#from userinput import userinput

app = Flask(__name__,
            static_url_path='', 
            static_folder='staticpages')
CORS (app)

@app.route('/')
def hello_world():
    return 'Hello World'
# curl http://127.0.0.1:5000/

@app.route('/shop')
def getAllShop():
    return jsonify(ShoppingDAO.getAllShop())
# curl http://127.0.0.1:5000/shop

# find By dept
@app.route('/shop/<string:Dept>', methods =['GET'])
def findShopByDept(Dept):
    return jsonify(ShoppingDAO.findShopByDept(Dept))
# curl http://127.0.0.1:5000/shop/Spud

# find By ID
#@app.route('/shop/<int:ID>')
#def findShopByID(ID):
#    return jsonify(ShoppingDAO.findShopByID(ID))
# curl http://127.0.0.1:5000/shop/1    

@app.route('/shop/<int:ID>', methods =['GET'])
def findShopByID(ID):
    foundShop = ShoppingDAO.findShopByID(ID)
    return jsonify(foundShop) 


# Create

@app.route('/shop', methods=['POST'])
def createShop():
       
    if not request.json:
        abort(400)
    if not 'ID' in request.json:
        abort(400)
    Shop={
        "Dept": request.json['Dept'],
        "Name":request.json['Name'],
        "Amount":request.json['Amount']
    }
    values = (Shop['Dept'], Shop['Name'], Shop['Amount'])
    newId = ShoppingDAO.createShop(values)
    Shop['ID'] = newId
    return jsonify(Shop)


    # curl -X POST -d "{\"ID\":1, \"Dept\":\"Fresh\", \"Name\":\"Test\", \"Amount\": 5}" -H Content-Type:application/json http://127.0.0.1:5000/shop



@app.route('/shop/<int:ID>', methods=['PUT'])
def updateShop(ID):
    foundShop = ShoppingDAO.findShopByID(ID)
    if not foundShop:
        abort(404)
    
    if not request.json:
        abort(400)
    reqJson = request.json
    if 'Amount' in reqJson and type(reqJson['Amount']) is not int:
        abort(400)

    if 'Dept' in reqJson:
        foundShop['Dept'] = reqJson['Dept']
    if 'Name' in reqJson:
        foundShop['Name'] = reqJson['Name']
    if 'Amount' in reqJson:
        foundShop['Amount'] = reqJson['Amount']
    values = (foundShop['Dept'],foundShop['Name'],foundShop['Amount'],foundShop['ID'])
    ShoppingDAO.updateShop(values)
    return jsonify(foundShop)

# curl -X PUT -d "{\"Dept\":\"Monday\", \"Name\":\"Mondy\", \"Amount\": 50}" -H Content-Type:application/json http://127.0.0.1:5000/shop/3

# Delete
@app.route('/shop/<int:ID>' , methods=['DELETE'])
def deleteShop(ID):
    ShoppingDAO.deleteShop(ID)
    return jsonify({"done":True})

# curl -X DELETE http://127.0.0.1:5000/shop/2

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

【问题讨论】:

  • 错误代码 400 表示这是服务器端,因此您必须包含一些服务器端代码。
  • 抱歉,我现在已经添加了。

标签: javascript python html ajax flask


【解决方案1】:

value 属性是一个字符串,因此测试 type(reqJson['Amount']) is not int 成功,您正在报告错误。

创建 JSON 时将金额转换为整数:

shop.Amount = parseInt(form.querySelector('input[name="Amount"]').value)

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 2017-05-17
    • 2019-05-16
    • 2020-02-02
    • 2011-04-19
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多