Posts

Showing posts from December, 2013

POSTing ajax data in query-string format to Django

1. Sending query-string formatted data with jQuery.ajax() The ' data' setting of jQuery.ajax() setting may either contain a String or a PlainObject . In case of a string, the data is sent 'as-is'. See example 1: $.ajax({    type: 'POST',    data: "test,1,2,3"); -> data will be sent as "test,1,2,3" In case of an object, it is automatically converted to a query-string, no matter what the 'contentType' setting is. See example 2: $.ajax({    type: 'POST',    data: {"test": 1, "test2"="two"}); -> data will be sent as "?test=1&test2=two" Objects must be a set of key/value pair(s). If any value is an array, the conversion depends on the traditional setting. If 'traditional ' is set to true , the ajax() method will only be able to send shallow objects: a value can be an indexed array, but not an associative array ( use json instead ). The conversion looks l...

POSTing json data to Django (ajax)

1. jQuery.ajax() doesn't automatically encode data to JSON Your client code is responsible for encoding its data into a json string, otherwise jQuery.ajax() will try to send it as a query-string. Even if you set the 'contentType' to "application/json" and provide an object that can be serialized into json, the ajax() function will turn it into a query-string. $.ajax({    type: 'POST',     contentType: "application/json",     data: {"test": 1}); -> data will be sent as "?test=1" Note: as long as you don't need to send (complex) objects, it may be easier to send query-string formatted data to Django. See this post for more details. So, your client code will need to turn its data into a json string, before passing it to ajax() . $.ajax({    type: 'POST',     contentType: "application/json",     data: JSON.stringify({"test": 1})); This also works on objects: var tmpObject = ne...