【问题标题】:How to load a section of the page using ajax when load page?加载页面时如何使用ajax加载页面的一部分?
【发布时间】:2017-01-18 04:00:07
【问题描述】:

我想在页面加载时使用 ajax 从数据库中加载一些数据。但它不会工作或显示数据。

我在控制器端的代码。

public ActionResult Index(int? respondentId)
{
   return View();
}

[HttpPost]
public ActionResult GetIntroParagraph(int? id)
{
    int id = id?? 111;
    Paragraph p= ParagraphDb.GetParagraghByRespondentId(id);
    return Content(p.Introduction);
}

还有我在视图上的代码,

<script>
    $(function () {
        var data = undefined;
        $.load(@Url.Action("GetIntroParagraph","Landing"),data,function(result) {
            $('#paragraph').append(result);
        });
    });
</script>

<div id="paragraph"></div>

我哪里弄错了?

【问题讨论】:

  • 如果您在浏览器控制台中遇到任何错误怎么办? p.Introduction 有值吗?
  • @Stephen Muecke 'p.Introduction' 没有价值。我设置了一个断点。它不会进入 GetIntroParagraph 方法。
  • 那么您在浏览器中遇到了什么错误? (以及您在'@Url.Action("GetIntroParagraph","Landing")' 周围缺少的引号)
  • @Stephen Muecke 感谢您在控制台中检查错误的提示,现在我可以正常工作了。我应该使用 $.get 或 $.post,它不会识别 $.load。
  • .load() 的语法错误 - 它必须是 $(someElement).load(url, data); - 请参阅 documentation

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


【解决方案1】:

由于没有人回答,这是我自己找到的解决方案。

1.我必须在前面引用jquery文件。
2.使用$.post而不是$.load

@Scripts.Render("~/bundles/jquery")

<script>
$(function () {

    var data = undefined;
    $.post('@Url.Action("GetIntroParagraph","Landing")', data, function (result) {
        $('#paragraph').append(result);
    });
});
</script>

【讨论】:

  • 您可以使用.load() - $('#paragraph').load('@Url.Action("GetIntroParagraph","Landing")';(请参阅问题的cmets)
  • @Stephen Muecke 我尝试使用 $('#paragraph').load('@Url.Action("GetIntroParagraph","Landing")', data, function (result) { $( '#paragraph').append(result); });不知何故,它显示了两次结果数据。这很奇怪。
  • 阅读上一条评论 - 代码只是$('#paragraph').load('@Url.Action("GetIntroParagraph","Landi‌​ng")';(完全正确)
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 2014-12-04
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多