简体   繁体   中英

Sending form JSON data to server via AJAX

I want to manually send my form data in JSON format to the server. I changed my form data to a JSON fomat below. The data I have in my clients-side javascript is in JSON (ie {"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

{ '{"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

Set processData : false and contentType : '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)

Please directly parsed your object to json. for example: JSON.Stringfy(obj)

You can just serialize the form and bodyparser will parse it into json for you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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