如何使用 AJAX 和 JQuery 使用 JSON 数据实现 PUT 调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13056810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:15:14  来源:igfitidea点击:

How to implement a PUT call with JSON data using AJAX and JQuery?

jqueryajaxjsonput

提问by Rail24

I've looked around and tried many different methods, but can't seem to pass actual data to my controller's function.

我环顾四周并尝试了许多不同的方法,但似乎无法将实际数据传递给我的控制器函数。

Here is some code:

这是一些代码:

        var URL = "/Timesheet/Timesheet/UpdateEntry";

        var dataObject = { 'newWeekEntry': newEntry, 'oldWeekEntry': oldEntry };

        alert(JSON.stringify(dataObject));

        $.ajax({
            url: URL,
            type: 'PUT',    
            data: JSON.stringify(dataObject),
            dataType: 'json',
            success: function(result) {
                alert("success?");
            }
        });

newEntryand oldEntryare both objects.

newEntry并且oldEntry都是对象。

The alertline outputs this (with some properties removed, just for brevity):

alert行输出这个(删除了一些属性,只是为了简洁):

{"newWeekEntry":{"MondayHours":2,"TuesdayHours":2,"WednesdayHours":5,"ThursdayHours":5,"FridayHours":"4","SaturdayHours":0,"SundayHours":0},"oldWeekEntry":{"MondayHours":2,"TuesdayHours":2,"WednesdayHours":5,"ThursdayHours":5,"FridayHours":2,"SaturdayHours":0,"SundayHours":0}}

When I debug my controller action ("UpdateEntry"), the two parameters are filled with the TimesheetEntryclass default parameters (0).

当我调试控制器操作(“UpdateEntry”)时,这两个参数填充了TimesheetEntry类默认参数 (0)。

Am I passing this in properly?

我是否正确传递了这个?

回答by InPursuit

The dataTypeattribute is only used when you're getting data from the server. You should be setting contentTypeto application/jsonwhen sending data to the server.

dataType属性仅在您从服务器获取数据时使用。您应该在向服务器发送数据时设置contentTypeapplication/json

回答by Jayadeep KM

$.ajax({
        url: window.serverUrl + 'student/event/' + eventId,
        type: 'put',
        data: JSON.stringify(data),
        headers: {
            'x-auth-token': localStorage.accessToken,
            "Content-Type": "application/json"
        },
        dataType: 'json'
})

This worked for me

这对我有用

回答by user1524615

Use headers: {"X-HTTP-Method-Override": "PUT"}and override the POSTrequest type. It works on my project...

使用 headers:{"X-HTTP-Method-Override": "PUT"}并覆盖POST请求类型。它适用于我的项目...

$.ajax({
    type: 'POST', // Use POST with X-HTTP-Method-Override or a straight PUT if appropriate.
    dataType: 'json', // Set datatype - affects Accept header
    url: "http://example.com/people/1", // A valid URL
    headers: {"X-HTTP-Method-Override": "PUT"}, // X-HTTP-Method-Override set to PUT.
    data: '{"name": "Dave"}' // Some data e.g. Valid JSON as a string
});