javascript - 使用按钮从服务器加载更多数据,无需刷新页面

标签 javascript ajax asp.net-core

我的服务器从 xml 加载文章,并将它们发送到我的 View 。 我只想发送一些文章,而不是全部,并向用户提供一个按钮来加载更多文章。 但是如何在不刷新页面的情况下将这些新数据发送到我的 View ,是否可以只更新模型?

public IActionResult Index()
        {
            List<Article> articles = new List<Article>();

            XmlSerializer serializer = new XmlSerializer(typeof(List<Article>), new XmlRootAttribute("Articles"));
            using (StreamReader reader = new StreamReader(HostingEnvironment.WebRootPath + @"/articles/articles.xml"))
            {
                articles = (List<Article>)serializer.Deserialize(reader);
            }

            return View(articles);
        }


<div id="articles">
    @foreach (Article art in Model)
    {
        var articleImage = "/images/articles/" + art.Image + ".jpg";
        <article>
            <div class="article_title_and_date">
                <h2 class="article_title">@art.Title</h2>
                <p class="article_date">@art.Date</p>
            </div>
            <img src="@Url.Content(articleImage)" alt="image">
            <p>
                @art.Text
            </p>
        </article>
    }
</div> 

最佳答案

您将需要实现一些 JavaScript 来通过 API 与您的服务器通信。下面是每次单击按钮时从服务器获取一些不同数据的基本示例。

var postNumber = 1;

document.getElementById('getNextPost').addEventListener('click', function() {
  var currentPost = document.getElementById('currentPost');
  var url = `https://jsonplaceholder.typicode.com/posts/${postNumber++}`;

  fetch(url)
    .then(response => response.json())
    .then(json => currentPost.innerHTML = json.body)
})
<div id="currentPost">Some static content from the server</div>
<button id="getNextPost">Get Next Post</button>

此示例使用 JSON 端点;但是,您可以使用 .then()

内的 window.DOMParser 从 XML 端点读取值
new window.DOMParser()).parseFromString(str, "text/xml")

关于javascript - 使用按钮从服务器加载更多数据,无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53912562/

相关文章:

c# - 尝试在 ASP.NET Core 应用程序中使用 SmtpClient 发送电子邮件时出现错误

javascript - 如何将子资源的新路由渲染到应用程序侧边栏导出中?

asp.net - 如何在 asp.net 网页中实现 html 表单 - asp.net 中的两种表单问题

php - Jquery ajax 正在切割数组?

visual-studio - 如何更改 VS 2017 RC .csproj 项目的目标框架(从核心到经典)?

c# - 如何使用 lambda 表达式进行验证以验证某个小时是否为某个 "type"(必须为 hh :00 or hh:30)

javascript - 为什么 React Redux 中的 props 没有被映射状态更改为 props

javascript - 如何使用 React 或 Angular 创建仅在需要时加载的可重用画廊

javascript - 向下滚动时如何将 div 的底部粘贴到屏幕顶部?

javascript - 空字符串传递给 jquery.unobtrusive-ajax.js 中的 getElementById() :16