使用 ajax 传递 JSON 格式的数据不起作用

passing JSON formatted data with ajax is not working

提问人:ym733 提问时间:9/21/2023 最后编辑:Md Farid Uddin Kironym733 更新时间:9/22/2023 访问量:68

问:

我正在尝试使用一些 JSON 数据在我的控制器中调用一个操作,它似乎正在到达该操作,但数据都是空的。

这是我的 Ajax 函数的样子:

function AjaxPost(url, data) {
    $.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        //I tried adding the following but to no avail:
        processData: true,
        traditional: true,
        success: function (response) {
            //success code
        },
        error: function (err) {
            console.error(err);
        }
    });
}

这就是我制作 AjaxPost 函数的方式:

<a href="javascript:AjaxPost('./Chat/PrivateChat', {id:123, username:'username', connectionID:'connectionID'})">

这是我调用的控制器:

public IActionResult PrivateChat(int id, string username, string connectionID)
{
    //at this point
    //id = 0
    //username = null
    //connectionID = null
}

我还尝试了来自以下来源的方法,但数据保持为空:

链接1

链接2

链接3

JavaScript C# ajax asp.net-core

评论

0赞 Rory McCrossan 9/21/2023
在 devtools 中检查请求 - 发送请求时数据实际上是空的,还是服务器端的模型绑定中的问题?
0赞 Rory McCrossan 9/21/2023
另外,切勿使用 .使用 addEventListener() 正确绑定事件处理程序。我还建议删除.你在这里不需要它,它可能会导致它解决的更多问题。href="javascript:..."traditional: true
0赞 ym733 9/22/2023
@RoryMcCrossan 问题出在模型绑定上,当我在 Ajax 请求之前通过控制台记录我的数据时,它似乎没问题,但是一旦我们通过 Ajax 请求,我的数据就消失了。我也知道使用 href javascript 并不理想,但我有不止一个锚点,它们都调用相同的方法
0赞 Rory McCrossan 9/22/2023
使用 console.log 是不一样的。发出 AJAX 请求后,需要检查 devtools 的“网络”选项卡,以查看其中包含的内容。但是,假设问题出在模型绑定器上,则需要显示更多 C# 代码来调试问题。JS 与问题无关。
0赞 sairfan 9/22/2023
在您调用函数的地方,在参数中,我认为它在那里无效的 json。

答:

0赞 Sankar Udaiyar 9/22/2023 #1

尝试添加 .它会起作用的。谢谢。!dataType: 'json'

评论

0赞 Community 9/25/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。
1赞 Md Farid Uddin Kiron 9/22/2023 #2

我正在尝试使用一些 JSON 数据在我的控制器中调用一个操作,它 似乎正在到达操作,但数据全部为空。

好吧,根据您的场景和描述,您将始终获得空数据。顺便说一句,您正在发送 Json 数据,您必须在控制器中使用 [FromBody] 包装 Request 模型,或者您应该将数据作为查询参数发布,如下所示:"http://localhost:5094/AjaxPostNull/PrivateChat2?id=" + data.id + "&username=" + data.username + "&connectionID=" + data.connectionID

让我们看一下实践,我们如何实现这一目标:

方式: FormBody 包装器:

请求型号:

public class AjaxRequestModel
 {
     public  int id { get; set; }
     public string username { get; set; }
     public string connectionID { get; set; }
 }

控制器签名:

public IActionResult PrivateChat([FromBody] AjaxRequestModel ajaxRequestModel)
{
    //at this point
    //id = 0
    //username = null
    //connectionID = null

    return null;
}

注意:如果将请求与 json 模型一起发送,则应使用 [FromBody] 包装控制器

脚本:

@section scripts {
    <script>
        function PostAjaxRequest() {
            var url = "http://localhost:5094/AjaxPostNull/PrivateChat2?id=" + data.id + "&username=" + data.username + "&connectionID=" + username +;
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                // data: JSON.stringify(data),
                success: function (response) {
                    //success code
                },
                error: function (err) {
                    console.error(err);
                }
            });
        }
    </script>
}

输出:

enter image description here

enter image description here

替代方法:查询字符串

enter image description here

@section scripts {
    <script>
        function PostAjaxRequest() {
            

            var data = { id: 123, username: "Test User Name", connectionID: "My con ID" };


            var url = "http://localhost:5094/AjaxPostNull/PrivateChat2?id=" + data.id + "&username=" + data.username + "&connectionID=" + data.connectionID
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                // data: JSON.stringify(data),
                success: function (response) {
                    //success code
                },
                error: function (err) {
                    console.error(err);
                }
            });
        }
    </script>
}

注意:您还可以使用逗号分隔值通过data:

输出:

enter image description here

注意:如果您想了解更多信息,请参阅此官方文档