首页 > 解决方案 > 通过 ajax 发送一个带有 json 数据的 post 请求,但在端点中它不是作为 json 来的

问题描述

我正在使用 ajax 构建一个简单的发布请求,对此没有什么特别的:

$.ajax({
                type: 'POST',
                contentType: "application/json",
                dataType: 'json',
                url: 'https://nnn.beeceptor.com',
                data:{
                    country: "country",
                    customer_title: "customer_title",
                    date_of_birth: "date_of_birth",
                    education: "education",
                    email: "email",
                    first_name: "first_name",
                    institution: "institution",
                    last_name: "last_name",
                    pay_type: "pay_type",
                    phone: "phone",
                    way_of_contact: "way_of_contact",
                    work_experience: "work_experience"
                },
                success: function(data){
                    console.log(`success`)
                },
                error: function(data){
                    console.log(`error`);
                }
            })

现在我希望在端点中,我在正文中发送的数据以 json 的形式出现。

我该如何解决这个问题,以便数据以 json 格式到达端点。对于测试,您可以使用该端点来查看数据的格式。任何建议都非常感谢。

标签: jsonajax

解决方案


经过一番研究,我能够得出一个答案。在 ajax 请求上需要定义 header 中的内容,如下所示:

 headers: {
                    "content-type": "application/json;charset=UTF-8" // Add this line
                },

在数据属性中:

data: JSON.stringify(data_object)

这解决了我的问题


推荐阅读