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

时间:2012-10-24 20:02:23

标签: jquery ajax json put

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

以下是一些代码:

        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?");
            }
        });

newEntryoldEntry都是对象。

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}}

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

我是否正确传递了这个?

3 个答案:

答案 0 :(得分:30)

dataType属性仅在从服务器获取数据时使用。将数据发送到服务器时,您应该将contentType设置为application/json

答案 1 :(得分:3)

使用标头:{"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
});

答案 2 :(得分:2)

$.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'
})

这对我有用