如何将HTML的POST数据转换为JSON格式?

6
  'recipient.firstName': 'Fred',
  'recipient.lastName': 'Johnson'

有没有一种优雅的方法可以把这个转化为:
var recipient = {
  firstName: 'Fred',
  lastName: 'Johnson
}

在前端使用JS?我想POST JSON,但是似乎用HTML并不容易实现。因此,我想用jQuery拦截POST请求,并将其格式化为我想要的JSON。
编辑:出于清晰起见,我保留了上面的原始问题,但是如果您仔细阅读,您会发现我遇到的问题不是将数据通过AJAX POST到REST API。这非常简单且已实现。正在动态构建表单,使用我创建的模板引擎,表单id和名称构建为表示嵌套数据的形式,例如recipient.firstName。但是,当我以JSON形式接收此数据传递到API端点时,我需要以编程方式将其从第一种格式转换为第二种格式,这实际上是问题所在。抱歉造成任何困扰,下面列出的答案解决了问题。

1
你应该先尝试一些东西,然后再提出问题。遍历属性,查找带有点的属性,并为这些属性创建子对象。这似乎并不难,我不想写代码阻碍你的学习经验。 - Ruan Mendes
1
是的Juan,那基本上就是我现在正在编写的内容。 - Anthony
将对象转换为字符串,将“recipient。”替换为空白,并解析该字符串。JSON.parse(JSON.stringify(original).replace(/recipient./g,'')) - Jules
4个回答

1
var recipient = [{firstName: "Fred",lastName: "Johnson"}]
                //:: CONVERT TO JSON
                recipient = JSON.stringify(recipient);
                //:: POST THE DATA 
                $.post(LINK_url,{post_recipient : recipient },json/*:: json not important, it can be auto guessed. delete ',json' */,function(output){
                    //var data =jQuery.parseJSON(output);});

如果我没理解错,您的输出是纯文本并且您需要将其转换为JSON格式,如果是这样,请尝试以下方法。

var recip = JSON.stringify[{ output }];
var data = jQuery.parseJSON(recip);
var viewdata='';
$.each(data, function(key, recipient){viewdata +=
recipient.firstName +" "+recipient.lastName+"<br/>"
})
prompt(viewdata);

0

更新

现在我知道你的服务器端是NodeJs,你只需要学习如何调用NodeJS服务器端方法:

如何从JQuery AJAX请求发送数据到Node.js服务器

所以你的方法是错误的,你有这个不必要复杂的数据字符串,想要拦截它。不要拦截任何东西,使用jQuery或JavaScript向您的服务器控制器或API发送格式良好的HTTP POST。您的API方法签名应该是:

DoSomethingWithRecipient(string firstName, string lastName);

你的收件人应该也有一个userId,但这取决于你。如果你没有使用服务器端框架来解析传入请求并将其映射到你的DoSomethingWithRecipient函数,比如PHP或ASP.NET,那么你很可能是在白费力气。

然后,使用jQuery,你只需要执行一个Ajax HTTP Post请求,就像这样:

var recipient = {
  firstName: 'Fred',
  lastName: 'Johnson'
}

var json = JSON.stringify(recipient);

$.ajax({
    url: '/MyUrl/DoSomethingWithRecipient',
    type: 'POST',
    dataType: 'json',
    data: json,
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
    },
    error: function (result) {
    }
});

为什么不在模板引擎中保留模板引擎格式的知识...在发布之前在模板引擎中构建JSON。 - Brian Ogden

0

使用jQuery和表单,通过serializeArray()forEach和其他对象:

$(function() {
  var recipient = $("#frm").serializeArray();
  var output = {}; // Declare an object.

  recipient.forEach(function(v, i) {
    output[v.name] = v.value; // Assign the current value to the current key.
  });

  $.ajax({
    url: "http://httpbin.org/post",
    type: "POST",
    data: JSON.stringify(output), // Send the object.
    contentType: "application/json",
    success: function(response) {
      //console.log(response);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm" method="post">
  firstName:
  <br/>
  <input id="firstName" name="firstName" type="text" value="Fred" />
  <br />lastName:
  <br/>
  <input id="lastName" name="lastName" type="text" value="Johnson" />
  <br />age:
  <br/>
  <input id="age" name="age" type="text" value="30" />
</form>

在请求中,您发送: {{link1:输入图像描述}}

-2

这是我正在使用的:

_.forOwn(options, function(value, key) {
  if(key.indexOf('.') != -1){

    var split = key.split('.')

    if( !global[split[0]] ) {
      global[split[0]] = {}
    }

    global[split[0]][split[1]] = value
  }
});

在后端使用NodeJS时,使用global

目前看起来似乎可以,如果最终决定使用它,我会再报告的。


你的方法需要修正,可以尝试使用Ajax和NodeJs一起使用,可以参考这个链接:https://dev59.com/t2Yr5IYBdhLWcg3wssGP - Brian Ogden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接