You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

项目中jQuery Ajax无报错但无法正常工作问题排查

问题描述

我需要通过Ajax将数据加载到id为commentList的div中,同时借助表单通过Ajax把数据提交到名为CreateComment的Action;创建评论完成后,重新加载commentList里的数据。但目前存在两个问题:表单无法提交数据,且页面加载后数据也无法加载到commentList div中。

表单代码

<form class="active" asp-controller="Product" asp-action="CreateComment" id="review_form"
      data-ajax="true" data-ajax-method="post" data-ajax-mode="replace"
      data-ajax-update="#listcomment" data-ajax-success="Success">
    <input type="hidden" name="comment.ProductId" value="@Model.ProductId" />
    <label>
            متن
    </label>
    <textarea name="comment.Comment" id="comment_Comment"></textarea>
    <button class="form-btn" type="submit">ثبت نظر</button>
</form>

CreateComment Action代码

public IActionResult CreateComment(ProductComment comment)
{
    comment.CreateDate = DateTime.Now;
    comment.IsDelete = false;
    comment.UserId = _userService.GetUserIdByUserName(User.Identity.Name);

    _productService.AddComment(comment);

    return View("ShowComments", _productService.GetProductComments(comment.ProductId));
}

目标div代码

<div class="small-12 medium-5 large-5 columns" id="commentList">
    <div class="fr-border"></div>
</div>

Ajax脚本代码

<script src="/js/jquery.unobtrusive-ajax.min.js"></script>
<script>
    function Success() {
        $("#comment_Comment").val("");
    }
    
    $(function () {
        $("#commentList").load("/Product/ShowComments/@(Model.ProductId)");
    });
</script>
问题排查与修复方案
  • 表单Ajax更新目标错误:表单的data-ajax-update属性值是#listcomment,但目标div的id是commentList,需要改成#commentList,这样提交成功后才能正确替换目标div的内容。
  • 脚本加载顺序错误:必须先加载jQuery库,再加载jquery.unobtrusive-ajax.min.js,否则Unobtrusive Ajax无法正常工作。调整加载顺序如下:
    <script src="/js/jquery.min.js"></script>
    <script src="/js/jquery.unobtrusive-ajax.min.js"></script>
    
  • 模型绑定优化:表单中输入框的name属性comment.ProductId可简化为ProductId,ASP.NET Core模型绑定会自动匹配ProductComment类的属性名,无需额外前缀。
  • 检查ShowComments视图:确认ShowComments视图是否正确渲染评论列表的HTML片段,load()方法依赖该视图返回有效内容。
  • 验证数据流程:检查_productService.AddComment是否将评论正确存入数据库,以及_productService.GetProductComments是否能查询到新增的评论数据。
  • 路由正确性验证:通过浏览器开发者工具查看/Product/ShowComments/@Model.ProductId生成的请求URL,确认该请求是否返回预期的评论内容。

内容的提问来源于stack exchange,提问作者Ghasem Shahrokhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:01:01