繁体   English   中英

jQuery Ajax PUT 请求

[英]jQuery Ajax PUT request

我尝试使用此代码执行 PUT 请求:

var body_user_update = JSON.stringify({
    "surname": document.getElementById(userID + "_surnameTextbox").value,
    "firstname": document.getElementById(userID + "_firstnameTextbox").value,
    "token": document.getElementById(userID + "_tokenTextbox").value
});

$.ajax({
    dataType: "json",
    url: "http://" + serverName + "/user/" + userID,
    type: "PUT",
    data: body_user_update,
    success: function (data) {
        // doing some stuff
    },
    error: function (message) {
        // error alert
    }
});

所以问题是我总是在错误函数中结束。 我发现的一切都是正确的,所以我不知道错误是什么。

我已经在没有JSON.stringifycontentType: "application/json"而不是或与dataType: "json"一起尝试了它。 切换浏览器也不会改变任何东西。

url 100% 正确,对象body_user_update也是body_user_update (至少surnamefirstnametoken的值)

编辑:我尝试了 Postman 的请求并得到了这个:

{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13", "title": "不支持的媒体类型", "status": 415, "traceId": "|94c1b46 -45b6529063414be7。” }

您的服务器显示“415 不支持的媒体类型”。 这意味着您的请求没有正确设置Content-Type标头。

显然,您的服务器需要 JSON 编码的数据。 因此,您需要将内容类型标头设置为application/json并防止 jQuery 进一步处理您的数据:

$.ajax({
    url: "http://" + serverName + "/user/" + userID,
    type: "PUT",
    contentType: 'application/json',
    processData: false,
    data: JSON.stringify({
        surname: $("#" + userID + "_surnameTextbox").val(),
        firstname: $("#" + userID + "_firstnameTextbox").val(),
        token: $("#" + userID + "_tokenTextbox").val()
    })
}).done(function (data) {
    // doing some stuff
}).fail(function (error) {
    // error alert
});

如果您多次需要该操作,请创建一个辅助函数:

$.putJSON = function (endpoint, data) {
    return $.ajax({
        url: "http://" + serverName + endpoint,
        type: "PUT",
        contentType: 'application/json',
        processData: false,
        data: JSON.stringify(data)
    }).fail(function (error) {
        // error alert
    });
});

// later ...

$.putJSON("/user/" + userID, {
    surname: $("#" + userID + "_surnameTextbox").val(),
    firstname: $("#" + userID + "_firstnameTextbox").val(),
    token: $("#" + userID + "_tokenTextbox").val()
}).done(function (data) {
    // doing some stuff
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM