简体   繁体   English

以序列化方式与JSON发送数据

[英]Sending data as serialized vs json

I'm sending data to a server via JavaScript for a REST API (this will be inside a PhoneGap app hence using jQuery rather than any server code). 我正在通过JavaScript将数据发送到REST API的服务器(这将在PhoneGap应用程序内部,因此使用jQuery而不是任何服务器代码)。 I'm building my own API so I have flexible options, but I wonder if there is a preferred way to handle POST data. 我正在构建自己的API,因此我有灵活的选择,但是我想知道是否存在处理POST数据的首选方法。 I use JSON for the GETs, so should I be using it for the POSTs? 我将JSON用于GET,所以我应该将其用于POST吗?

What is the better way to send it? 有什么更好的发送方式?

1) Using the serialize method and then sending it as data, eg : 1)使用序列化方法,然后将其作为数据发送, 例如

$('form').submit(function(e){

    e.preventDefault();

    var form = $(this);

    $.ajax({
        type: 'POST',
        url: form.attr('action'),
        data: form.serialize(),
        success: function(response){
            // handle response
        },
        error: function(a,b,c) {
            // handle error
        }   
    });

});

or 2) sending it as a JSON object like: 或2)将其作为JSON对象发送,例如:

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

$('form').submit(function(e){

    e.preventDefault();

    var form = $(this);

    $.ajax({
        type: 'POST',
        url: form.attr('action'),
        data: JSON.stringify(form.serializeObject()),
        success: function(response){
            // handle response
        },
        error: function(a,b,c) {
            // handle error
        }   
    });

});

Your second example does pretty much what $.ajax and .serialize() do internally, and the POST data is always sent as a string anyway, so it should'nt really matter one way or the other. 您的第二个示例几乎完成了$.ajax.serialize()在内部所做的事情,并且POST数据始终始终以字符串形式发送,因此,它实际上并没有关系。 The first example seems cleaner and easier to read, so that's an advantage. 第一个示例看起来更清晰,更易于阅读,所以这是一个优势。

Create an empty array, keep on pushing the individual form fields to the array, JSON.stringify the array, and send it via POST. 创建一个空数组,继续将各个表单字段推入数组,JSON.stringify数组,然后通过POST发送。

var formData = [];
//Push individual form elements to this aray, preferably in a "key" : "value" format.
var payload = JSON.stringify(formData);
//Then just send it to the server.

The good part with a JSON object is that you can read it from a variety of server side languages, without any effort.. JSON对象的优点在于您可以毫不费力地从多种服务器端语言中读取它。

Plus, you can even use 'key' : 'value' pairs inside the JSON object to manually get the value for each field at the server. 另外,您甚至可以在JSON对象中使用“键”:“值”对来手动获取服务器上每个字段的值。

In your question you don't specify what you mean by "better way," so perhaps you should edit your question to clarify that. 在您的问题中,您没有指定“更好的方式”的意思,因此也许您应该编辑问题以阐明这一点。 For example, are you specifically concerned with performance, memory usage, etc. ? 例如,您是否特别关注性能,内存使用情况

However, in a very general sense I would say the better way to do this type of thing is to go with the approach that you find easier to read, because that's the approach that will be easier to debug, extend, and modify over the course of time. 但是,从一般意义上讲,我想说做这种事情的更好方法是采用您认为更易于理解的方法,因为在整个过程中,这种方法将更易于调试,扩展和修改。时间。 Looking only at the client side code, your first approach appears to be easier to read, but if you are responsible for the server side, you should consider that too. 仅查看客户端代码,第一种方法似乎更易于阅读,但是如果您负责服务器端,则也应该考虑这一点。 Go with the approach that you think will be easier to maintain overall . 采用您认为更易于整体维护的方法。

Finally, you don't indicate in your question whether you are going to publish the REST API for others to use, but if you are, then the most important factor is actually how easy it is to read and understand the API. 最后,您没有在问题中指出是否要发布供他人使用的REST API,但是如果您愿意,那么最重要的因素实际上是阅读和理解API的难易程度。 By that measure, you should probably use JSON in both your GETs and POSTs. 通过这种方式,您可能应该在GET和POST中都使用JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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