【问题标题】:AJAX Post issue with ASP.NETASP.NET 的 AJAX 发布问题
【发布时间】:2019-08-22 21:06:40
【问题描述】:

我在发布数据时遇到问题。首先,我尝试使用简写 $.post 并得到 415 响应。该站点上的其他一些帖子建议改用 $.ajax 方法并设置一些标题。我这样做了,当我使用 $.ajax 方法时,数据似乎没有传递到服务器,因为后端的方法中断并说没有具有该 ID 的数据,这是不正确的。下面你可以看到这两种方法。该速记帖子目前已被注释掉。

$(".Set_set").click(function () {

        let setID = $(this).attr("data-id");
        $.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep",
            data: { id: setID },
            dataType: "json",
            headers: {
                "Content-Type": "application/json",
            },
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })


           /* 
            $.post("https://localhost:44327/workout/addRep", 
              { id: setID }, function (data) {
                console.log(data)
            })

 */

    }
    )

})

当我使用 $.ajax 方法时,浏览器中的 headers 部分会在“Request Payload”子部分下显示“id=3”。

当我使用 $.post 方法时,“请求有效负载”部分不存在。相反,有一个“表单数据”部分,它将显示“id:3”

如果有帮助,这里是后端代码:

[HttpPost]
    public IActionResult addRep([FromBody]int id)
    {
        //id is the setid

        ExerciseSet exerciseSet = context.Exercise_Sets.Where(c => c.ID == id).Single();



        return Ok(exerciseSet);
    }

【问题讨论】:

  • 从请求中删除标头
  • @MuhammadOmerAslam 我这样做了,但又得到了 415 错误。
  • 这意味着您的服务器不接受媒体格式,请参阅post
  • @MuhammadOmerAslam 阅读后,我将数据编辑为仅包含 id,而不是 JSON.stringify({id: setID})。我将数据设置为“setID”并且它有效。感谢您的链接。您对它为什么会这样工作有任何见解吗?
  • 这取决于$(this).attr("data-id")里面的内容

标签: jquery asp.net ajax post asp.net-ajax


【解决方案1】:

$.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep",
            data:JSON.stringify({ id: setID }) ,
            dataType: "json",
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })
            
    //OR  
    
    $.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep?id="+setID,
            dataType: "json",
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })
            
            

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-10
    • 2015-11-11
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多