【问题标题】:Jquery - Server can't read data sent from AjaxJquery - 服务器无法读取从 Ajax 发送的数据
【发布时间】:2022-02-15 17:52:24
【问题描述】:

我目前正在使用 ajax 从我的 Web 应用程序向 api 服务器发送数据。 但是服务器无法读取我的数据,因为我的数据的typeData与邮递员发送的typeData不同。

我正在测试从邮递员发送数据并且工作正常。 这是通过邮递员发送数据的捕获。

这是我的 ajax 代码

data = {
    nama_lengkap: "user name",
    nama_panggilan: "user",
    ttl: "new york, 10 april 1999",
    jenis_kelamin: "male",
    agama: "-",
    email: "username@mailinator.com",
    no_telp: "1234567",
    nama_ayah: "Johnson",
    nama_ibu: "Kadita",
    pendidikan_terakhir: "S1",
    organisasi: "-",
    kejuaraan: "-",
};

obj = JSON.stringify(data);
t = Cookies.get("user");

$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        accept: "application/json",
    },
});
$.ajax({
    type: "POST",
    timeout: 0,
    headers: {
        Accept: "application/json",
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + t);
    },
    url: "http://localhost:8000/api/anggota/store",
    contentType: "application/json",
    data: obj,
    dataType: "json",
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status, err) {
        console.error(JSON.parse(xhr.responseText));
    },
});

但我收到了这样的错误响应文本

{
    "success": false,
    "code": 500,
    "message": "Gagal",
    "errors": [
        {
            "nama_lengkap": [
                "The nama lengkap field is required."
            ],
            "nama_panggilan": [
                "The nama panggilan field is required."
            ],
            "ttl": [
                "The ttl field is required."
            ],
            "jenis_kelamin": [
                "The jenis kelamin field is required."
            ],
            "agama": [
                "The agama field is required."
            ],
            "email": [
                "The email field is required."
            ],
            "no_telp": [
                "The no telp field is required."
            ],
            "nama_ayah": [
                "The nama ayah field is required."
            ],
            "nama_ibu": [
                "The nama ibu field is required."
            ],
            "pendidikan_terakhir": [
                "The pendidikan terakhir field is required."
            ]
        }
    ]
}

嗯,我的代码有什么问题?任何线索都有帮助。

谢谢

【问题讨论】:

  • 控制台是否出现跨域错误?
  • 我的控制台没有跨域错误。
  • http://localhost:8000同一个端口运行这段代码?
  • 是的。我的 api 和 web 在同一个端口上运行。我认为问题不在于那里。因为我成功登录、注销和注册。但数据格式是 FormData 而不是像我上面的代码那样的原始 json。
  • Please don't add SOLVED to the title of your question。如果已通过答案解决,您可以接受该答案,如果您自己解决了问题,请write your own answer 并接受。

标签: jquery ajax postman


【解决方案1】:

你不应该使用Json.Stringify()

直接使用数据对象即可。

试试这个:

data = {
    nama_lengkap: "user name",
    nama_panggilan: "user",
    ttl: "new york, 10 april 1999",
    jenis_kelamin: "male",
    agama: "-",
    email: "username@mailinator.com",
    no_telp: "1234567",
    nama_ayah: "Johnson",
    nama_ibu: "Kadita",
    pendidikan_terakhir: "S1",
    organisasi: "-",
    kejuaraan: "-",
};

t = Cookies.get("user");

$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        accept: "application/json",
    },
});
$.ajax({
    type: "POST",
    timeout: 0,
    headers: {
        Accept: "application/json",
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + t);
    },
    url: "http://localhost:8000/api/anggota/store",
    contentType: "application/json",
    data,
    dataType: "json",
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status, err) {
        console.error(JSON.parse(xhr.responseText));
    },
});

【讨论】:

  • 我在使用 JSON.stringify() 之前已经尝试过您的方法,但仍然无法正常工作。我尝试使用 JSON.stringify,因为我正在阅读文章,上面写着 “当向 Web 服务器发送数据时,数据必须是字符串。将 JavaScript 对象转换为带有 JSON 的字符串。 w3schools 中的 stringify()"
  • 我说不要使用stringify。其次,Ajax 不接受字符串,它只接受对象。您已经在发送带有原始格式的邮递员请求,这是一个对象
  • 是的。我明白你的意思。但即使没有 stringify,它仍然无法正常工作。
  • 把data Object变成const我的意思是这样的:const data = {}然后直接写在ajax函数里
  • 有效吗????
【解决方案2】:

stringify:

它的结果是JSON string

official docs中提取:

data 选项可以包含 key1=value1&key2=value2 形式的查询字符串,或 {key1: 'value1', key2: 'value2'} 形式的对象。

所以我建议你在发送到服务器时使用object格式。

【讨论】:

  • javascript对象和JSON对象一样吗?
【解决方案3】:

我的代码中的 typeData 没有错。主要问题是因为我在代码末尾声明了ContentType: false

应该是这样的

$.ajax({
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + t);
            },   
            url: "http://localhost:8000/api/anggota/store",
            method: "POST",
            timeout: 0,
            data: form_anggota,
            contentType: "application/json",
            dataType: "json",
            success: function (response) {
                console.log(response);
            },
            error: function(xhr){
                console.log(JSON.parse(xhr.responseText))
            }
        });

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多