Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Re : How to send empty array field with can.ajax

$
0
0
I think I've run into the same problem, which is a limitation of the default encoding used `application/x-www-form-urlencoded`. If you send data encoded as `application/json` you will be able to send with the expressive power of JSON, which should mean you can send nested data, or as in your case, empty lists.

Here's a way to configure all (local) AJAX requests to do this, using jQuery.ajaxPrefilter.

  1. $.ajaxPrefilter(function(options) {

  2.     // Restrict this behavior to requests aimed at our own backend.
  3.     var localOrigin = (document.location.protocol + '//' + document.location.host);
  4.     var isLocalRequest = (
  5.         (options.url.indexOf('://') === -1) ||
  6.         (options.url.slice(0, localOrigin.length) === localOrigin)
  7.     );

  8.     // Restrict to requests that send data in the request body.
  9.     var type = options.type.toLowerCase();
  10.     var isDataRequest = (
  11.         type === 'post' || type === 'put' || type === 'delete'
  12.     );

  13.     if (isLocalRequest && isDataRequest) {
  14.         options.processData = false;
  15.         options.contentType = 'application/json; charset=utf8';
  16.         options.data = $.toJSON(options.data);
  17.     }

  18. });
If you run this once, all future requests will be encoded as JSON. Hopefully this works, because I trimmed from a more sophisticated version. But you can get the basic idea.

Also you might need to configure your backend to accept and decode the JSON data, I use django-rest-framework which fortunately made this very easy.




Viewing all articles
Browse latest Browse all 3491