admin管理员组

文章数量:1133954

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?

$.ajax({
    url      : url,
    dataType : 'json', // I was pretty sure this would do the trick
    data     : data,
    type     : 'POST',
    complete : callback // etc
});

This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?

$.ajax({
    url      : url,
    dataType : 'json', // I was pretty sure this would do the trick
    data     : data,
    type     : 'POST',
    complete : callback // etc
});

This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.

Share Improve this question edited Apr 26, 2018 at 0:42 Sebastian Simon 19.5k8 gold badges60 silver badges84 bronze badges asked Oct 2, 2012 at 16:00 RedsandroRedsandro 11.3k15 gold badges80 silver badges111 bronze badges 4
  • 7 The dataType has no bearing on how the data is sent. It merely specifies what the type of data is you expect to have returned by the call. If you want to indicate to the server what the type of data is you are specifying in the data property you need to set the contentType property similar to contentType: "application/json" – Nope Commented Oct 2, 2012 at 16:05
  • Thanks for clarifying. But in that case, why do I need to specify the response type client-side if the server is providing a content-type header in the response? – Redsandro Commented Oct 2, 2012 at 20:20
  • 2 You don't have to specify it, by default jQuery will try and make an intelligent guess based on the MIME type of the response. However, by specifying it you are telling jQuery explicitly what type you are expecting from the server and jQuery will attempt to convert the response to an object of that type. Not specifying it and leaving jQuery take a guess may result in jQuery converting the response into an unexpected format, even though you sent JSON from the server. Check the documentation for more details on the dataType: api.jquery.com/jQuery.ajax – Nope Commented Oct 2, 2012 at 22:08
  • Possible duplicate of Jquery Ajax Posting json to webservice – Madura Pradeep Commented Apr 21, 2016 at 17:30
Add a comment  | 

4 Answers 4

Reset to default 287

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!

Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:

 var data = {USER : localProfile,  
        INSTANCE : "HTHACKNEY",  
        PAGE : $('select[name="PAGE"]').val(), 
        TITLE : $("input[name='TITLE']").val(), 
        HTML : html,
        STARTDATE : $("input[name='STARTDATE']").val(), 
        ENDDATE : $("input[name='ENDDATE']").val(),
        ARCHIVE : $("input[name='ARCHIVE']").val(), 
        ACTIVE : $("input[name='ACTIVE']").val(), 
        URGENT : $("input[name='URGENT']").val(), 
        AUTHLST :  authStr};
        //console.log(data);
       $.ajax({
            type: "POST",
           url:   "http://www.domian.com/webservicepgm?callback=?",
           data:  data,
           dataType:'jsonp'
       }).
       done(function(data){
         //handle data.WHATEVER
       });

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

本文标签: javascriptHow to send JSON instead of a query string with ajaxStack Overflow