【问题标题】:Ajax Jquery PUT request doesn't workAjax Jquery PUT 请求不起作用
【发布时间】:2017-08-13 11:19:17
【问题描述】:

我正在尝试使用 jQuery 向我的服务器发送一个 Ajax PUT 请求,但是当我 console.log 通过我的成功函数返回的数据时,我得到的数据与我尝试更新的数据完全相同。

这是我的 Ajax 请求:

$(".plus-button").on("click", function() {

    var handler = $(this).siblings(".editIngredientForm");

    var formData = {
        photoName: handler.children("#numberOfItems").prevObject[0][0]["value"],
        name: handler.children("#numberOfItems").prevObject[0][1]["value"],

        // Add + 1 to number of items in ingredient to account for the clicking on plus sign
        number: Number(handler.children("#numberOfItems").prevObject[0][2]["value"]) + 1,
    };

    var actionUrl = $(this).siblings(".editIngredientForm").attr("action");
    // console.log(formData);     

    $.ajax({
        url: actionUrl,
        data: formData,
        type: "PUT",
        success: function(data) {
            console.log(data);
        }
    })
});

这是处理更新的后端路由(Node JS):

app.put("/inventory/:id", isLoggedIn, function(req, res) {
    Ingredient.findByIdAndUpdate(req.params.id, req.body.item, { new: true }, function(err, updatedIngredient) {
        if (err) {
            console.log(err);
        } else {
            if (req.xhr) {
                res.json(updatedIngredient);
            } else {
                req.flash("success", "You successfully updated the Ingredient's info");
                res.redirect("/inventory/" + req.params.id);
            }
        }
    })
})

有谁知道我做错了什么?

【问题讨论】:

  • req.body.item 有值吗?
  • 确保你已经安装了body-parser并配置了中间件app.use(body.json());
  • 我不知道 node.js,但我看不到您将返回值更改为更新值的位置。
  • @RolandStarke 当我在 else{ 之后 console.log(req.body.item) 时,什么都没有打印出来。
  • @santoshsingh Body-parser 已安装,我添加了 app.use(bodyParser.json()),但它仍然不起作用。

标签: jquery node.js ajax


【解决方案1】:

这是我最终找到的解决方案:

$(".plus-button").on("click", function(){

    var handler = $(this).siblings(".editIngredientForm");
    var oldNumber = handler.find('input[name="item[number]"]').val();
    var newNumber = Number(oldNumber) + 1;
    var numberOfIngredient = $(this).parent("#changeQuantitiesButtons").siblings("#state-of-inventory").children("#number-of-ingredient");
    handler.find('input[name="item[number]"]').val(newNumber);

    var formData= handler.serialize();
    var actionUrl = $(this).siblings(".editIngredientForm").attr("action");   

    $.ajax({
        url:actionUrl,        
        data:formData,
        type:"PUT",              
        success: function(data){
           numberOfIngredient.html(newNumber);
        }
    })
});

我没有直接通过 Ajax put 请求发送数据,然后修改表单中的值,而是更改表单中的值并通过请求。

希望对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多