How can I use JQuery to post JSON data?

后端 未结 5 2117
无人及你
无人及你 2020-11-22 07:46

I would like to post Json to a web service on the same server. But I don\'t know how to post Json using JQuery. I have tried with this code:

$.ajax({
    typ         


        
5条回答
  •  余生分开走
    2020-11-22 08:16

    Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.

    var DoPost = function(url, body) {
        try {
            body = JSON.stringify(body);
        } catch (error) {
            return reject(error);
        }
        return new Promise((resolve, reject) => {
            $.ajax({
                    type: 'POST',
                    url: url,
                    data: body,
                    contentType: "application/json",
                    dataType: 'json'
                })
                .done(function(data) {
                    return resolve(data);
                })
                .fail(function(error) {
                    console.error(error);
                    return reject(error);
                })
                .always(function() {
                    // called after done or fail
                });
        });
    }
    

提交回复
热议问题