Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - jQuery: How to stop AJAX function escaping JSON string used to POST data

I need to serialize all inputs from a form into a JSON string.
With the help of this post, I can successfully create a valid string as below:

{"input01":"value01","input02":"value02","input03":"value03"}

However, when I try to use the string to POST data using jQuery's Ajax function, it seems to add backslashes to the string, resulting in the JSON string being sent using GET rather than POST. The loaded PHP page returns a $_GET array of:

[{"input01":"value01","input02":"value02","input03":"value03"}] =>

I have tested the JSON string using alert() to confirm the structure is correct before being used in the AJAX function.
Additionally, if I just manually type in the valid JSON string, the AJAX posts the data correctly.

My code is as follows:

var dataJSON = $.toJSON($('#form').serializeObject());
alert(dataJSON);

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: 'Query01=01&Query02=02',
    dataType: 'json',
    success: function(data){
       if (data==1){
         $('#wrap').load('ajax.php',dataJSON);
       }
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the default behaviour of $.ajax(). You can change it by setting the processData option to false. See $.ajax() options.

data  Object, String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

and

processData   Boolean Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...