【问题标题】:several key value for post http request vs one key and json value发布 http 请求的几个键值与一个键和 json 值
【发布时间】:2018-05-14 06:14:36
【问题描述】:

我想知道哪种方式是标准和正常的。 我发送一个包含很多键值对的 post http 请求,但我只能发送一个键和一个 json 字符串对象作为值。哪个更合适 谢谢

【问题讨论】:

  • 您使用什么支持技术?我使用 C# .NET
  • node js backed 技术

标签: json node.js http web request


【解决方案1】:

这取决于您的后端:如果它接收到一个对象,则使用第二个选项 {"myParamName:{"prop1":prop1,"prop2":prop2}} 如果它接收到多个参数,则使用选项一

在我的选项中,使用 json 语法并将一个对象发送到后面:当你有几个参数时发送几个参数很好,但是当你需要发送几十个时你会怎么做?

编辑:正如我在您的个人资料中看到的,您使用 C# 这里是 ajax 查询到 .NET WEB 方法的示例:

$("#save").on('click', function (event) {
    // setting the object of the back-end
    var obj = {};
    obj.Description = $("#Description").val().trim();
    obj.Reference = $("#Reference").val().trim();
    obj.Duration = $("#Duration").val();
    obj.Begin = $("#Begin").val();
    obj.End = $("#End").val();
    obj.Id = $("#Id").val();
    obj.Notes = $("#Notes").val().replace(/[\n\r]/g, '<br>');
    obj.Done = $("#Done").val() == "true" ? true : false;
    // to json format
    var json = JSON.stringify({ "toDo": obj });
    $.ajax({
        type: "POST",
        url: "Main.aspx/AddWork",
        contentType: "application/json; charset=utf-8",
        data: json,
        success: function (response) {
            // do what ever you want
        },
        error: function (jqXHR, textStatus, errorThrown) {
            var str = jqXHR.responseText;
            var obj = JSON.parse(str);
            console.log(obj.Message);
        } // end error
    }); // end ajax
});


// on the back end : we receive an object named toDo of type Data
[WebMethod]
public static void AddWork(Data toDo)
{
...
}

// the Data type is declared in the same web method :
public class Data
{
    public int Id { get; set; }
    public string Description { get; set; }
    public DateTime? Begin { get; set; }
    public DateTime? End { get; set; }
    public string Reference { get; set; }
    public int? Duration { get; set; }
    public bool? Done { get; set; }
    public string Notes { get; set; }

}

// Hope it helps

【讨论】:

  • thx 是的,我有很多领域。注意:我想实现一个后端服务器
  • 那你会使用什么后端技术?
  • 你会使用纯javascript,jquery吗?如果您提供代码示例,我可以在 jquery 中为您提供示例
  • 我使用统一的前端(游戏)和 nodejs 后端服务器我想发送 http post 请求
  • 不幸的是我不知道 node.js :-( 也没有统一你应该更好地解释
【解决方案2】:

标准和正常是只发送普通的application/x-www-form-urlencoded 数据。这种方法早在设计 JSON 之前就已经存在,您可以使用纯 HTML 表单提交生成 application/x-www-form-urlencoded 数据。

将您的数据编码为application/json,然后将其嵌入到application/x-www-form-urlencoded 中会产生更多的数据编码和解码工作,并增加更多可能的故障点。

JSON 提供的唯一优势是它对更复杂的数据结构(如数组和对象)具有原生支持……但扩展了 application/x-www-form-urlencoded 格式(至少由 PHP、body-parserPHP::ParseStr 支持) ) 添加。

您没有提到的选项只是简单的application/json,它在基于 HTTP 的 API 中很流行。它没有与纯 HTML 表单提交兼容的优势,但没有嵌入两种格式的复杂性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多