Invalid json in ajax request

The goal is to successfully complete the POST new job in the REST API of the marathon. I am using jQuery v1.12.4

The following code gets the values ​​from the form and prints a valid json to console.log. I checked it with JSONLint. But it does not seem to get to the server. here is the JSON that prints in the log and which I see in firebug:

{"id":"basic-0","cpus":"0.1","mem":"32","instances":"1","cmd":"while [ true ] ; do echo 'Hello Marathon' ; sleep 5 ; done"}

I get a 400 Bad Request, and then I see this crazy answer (in firebug):

{"message":"Invalid JSON","details":[{"path":"/instances","errors":["error.expected.jsnumber"]},{"path"
:"/cpus","errors":["error.expected.jsnumber"]},{"path":"/mem","errors":["error.expected.jsnumber"]}]
}

I have no idea what this answer means. Does this come from jQuery or server? Does anyone know of a working example of calling a REST API of a marathon from javascript?

Here is the code. Yes, I know that it is very bad practice to pass the username and password in the request, but I still have not figured out how to use basic authentication, but I still have not figured out how to enable SSL on the marathon web server. Baby steps ...

var $form = $('#appsubmit1');

$form.submit(function() {
    var form2json = JSON.stringify($('form').serializeObject());
    console.log(form2json);
    $.ajax({
      type: 'POST',
      url: 'https://user:pass@mesos-head.achillesv.net/marathon/v2/apps',
      data: form2json,
      dataType: 'json',
      contentType: "application/json; charset=utf-8",
      timeout: 10000 
    }).done(function(resp, status, xhr) { 
      console.log("ajax function done: ", status);
    }).fail(function(xhr, status, errmsg) { 
      console.log("error: ", status); 
      console.log("error: ", errmsg); 
    });      
    return false;
  });

Here is the code for the serializeObject function, which I did not write, but found found online. It works fine, except that it double quotes all values. I need numerical values ​​not to be specified. Unfortunately, I do not see where the code introduces double quotes, so I can not take them out. I am still working on it.

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
      if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
      } else {
        o[this.name] = this.value || '';
      }
    });
    return o;
  };

this.value regexp, , , 0,1, 3, 200,5 .. , , , - else .

+4
2

, , cpus, mem instances. json:

{
    "id": "basic-0",
    "cpus": 0.1,
    "mem": 32,
    "instances": 1,
    "cmd": "while [ true ] ; do echo 'Hello Marathon' ; sleep 5 ; done"
}
+2

var form2json = JSON.stringify($('form').serializeObject()); ... data: form2json, data: $("form").serialize()? , , stringify .

+2

Source: https://habr.com/ru/post/1649721/


All Articles