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

。_饼干妹妹 提交于 2019-12-03 17:30:49

问题


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

newEntry and oldEntry are both objects.

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

{"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 TimesheetEntry class default parameters (0).

Am I passing this in properly?


回答1:


The dataType attribute is only used when you're getting data from the server. You should be setting contentType to application/json when sending data to the server.




回答2:


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

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



回答3:


$.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



来源:https://stackoverflow.com/questions/13056810/how-to-implement-a-put-call-with-json-data-using-ajax-and-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!