简体   繁体   English

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

[英]Sending form JSON data to server via AJAX

I want to manually send my form data in JSON format to the server. 我想将JSON格式的表单数据手动发送到服务器。 I changed my form data to a JSON fomat below. 我将表单数据更改为下面的JSON格式。 The data I have in my clients-side javascript is in JSON (ie {"firstname":"john","lastname":"smith"} 我在客户端javascript中拥有的数据是JSON(即{"firstname":"john","lastname":"smith"}

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

    }
});

I am using body-parser and in my server.js code, I do console.log(req.body) but the data is shown in this format 我正在使用body-parser,在我的server.js代码中,我做了console.log(req.body),但是数据以这种格式显示

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

It added more curly braces. 它添加了更多的花括号。 Why is that? 这是为什么? How can i access the data in the server side 我如何在服务器端访问数据

dataType: 'application/json' will expect json response from server dataType: 'application/json'将期望来自server json响应

Set processData : false and contentType : 'application/json' [ Ref ] 设置processData : falsecontentType : 'application/json' [ 参考 ]

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" . processData:默认情况下,将处理作为对象传递给data选项的数据(从技术上讲,不是字符串),然后将其转换为查询字符串,以适合默认的内容类型"application/x-www-form-urlencoded" If you want to send a DOMDocument, or other non-processed data, set this option to false 如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false


contentType: When sending data to the server, use this content type. contentType:将数据发送到服务器时,请使用此内容类型。 Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. 默认值为“ application / x-www-form-urlencoded; charset = UTF-8”,在大多数情况下都可以。 If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent) 如果您将内容类型显式传递给$ .ajax(),则始终将其发送到服务器(即使没有发送数据)

Please directly parsed your object to json. 请直接将您的对象解析为json。 for example: JSON.Stringfy(obj) 例如:JSON.Stringfy(obj)

You can just serialize the form and bodyparser will parse it into json for you. 您只需序列化表单,bodyparser就会为您解析为json。

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

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

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