我的服务器从 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/