【发布时间】:2018-05-14 06:14:36
【问题描述】:
我想知道哪种方式是标准和正常的。 我发送一个包含很多键值对的 post http 请求,但我只能发送一个键和一个 json 字符串对象作为值。哪个更合适 谢谢
【问题讨论】:
-
您使用什么支持技术?我使用 C# .NET
-
node js backed 技术
标签: json node.js http web request
我想知道哪种方式是标准和正常的。 我发送一个包含很多键值对的 post http 请求,但我只能发送一个键和一个 json 字符串对象作为值。哪个更合适 谢谢
【问题讨论】:
标签: json node.js http web request
这取决于您的后端:如果它接收到一个对象,则使用第二个选项 {"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
【讨论】:
标准和正常是只发送普通的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-parser 和 PHP::ParseStr 支持) ) 添加。
您没有提到的选项只是简单的application/json,它在基于 HTTP 的 API 中很流行。它没有与纯 HTML 表单提交兼容的优势,但没有嵌入两种格式的复杂性。
【讨论】: