简体   繁体   中英

Post JSON-Data from PlayFramework form

Play Framework provides a way to access JSON-Data in a request-body via request().body().asJson() . Using form-helpers does not post data in JSON-format.

So, what is the best way, in a play-application, to convert the form-data to a json-object before passing it to the controller?

Thanks in advance.

When you retrieve request payload data you can use either BodyParsers (they use the Content-Type header to parse the payload into something else) or you can get the payload yourself via form binding or directly as JSON IF you have a JSON/textual payload in the request body.

In your case, you have a Content-Type of either application/x-www-form-urlencoded OR multipart/form-data . So you need to bind to that form with a helper class get that data and IF you really want to convert it to JSON you'll just add an additional step of inserting it in a ObjectNode.

If you want your form data as JSON, do the conversion directly on the frontend, if possible and send it in the body as Content-Type application/json .

Now, do you understand why what you want to do just adds additional complexity for no apparent gain?

1.Serialize the form to a JSON-Object

$.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;
};

2.Define an AJAX request with content type application/json

$.ajaxSetup({
    contentType: "application/json; charset=utf-8" 
});

function request(path, params, method) {
method = method || "POST";

$.ajax({
    url: path,
    type: method,
    data: params,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        //do something
    },
    error: function (xhr, ajaxOptions, thrownError) {
        //do something
    }
});
}

3.Send data after form submission

$(function() {
var url = "/api/route";

$('form').submit(function() {
    var json = JSON.stringify($('form').serializeObject());
    request(url, json);
    return false;
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM