通过 AJAX 将表单 JSON 数据发送到服务器

Sending form JSON data to server via AJAX

我想将我的表单数据以 JSON 格式手动发送到服务器。 我将表单数据更改为下面的 JSON 格式。 我在客户端 javascript 中的数据在 JSON 中(即 {"firstname":"john","lastname":"smith"}

$.ajax({
    type: 'POST',
    url: "http://localhost:3000/UserRegistration",
    dataType: 'application/json',
    data: JSONData,
    success: function(data) {

    }
});

我正在使用 body-parser,在我的 server.js 代码中,我使用 console.log(req.body) 但数据以这种格式显示

{ '{"firstname":"john","lastname":"smith"}': '' }

它添加了更多花括号。这是为什么?如何访问服务器端的数据

dataType: 'application/json' 将期望 json 来自 server

的响应

设置processData : falsecontentType : 'application/json'[Ref]

processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false


contentType: When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent)

请直接将您的对象解析为 json。例如:JSON.Stringfy(obj)

您只需序列化表单,bodyparser 就会为您将其解析为 json。

$.post('http://localhost:3000/UserRegistration', form.serialize(), function(data) {
    ...
});