简体   繁体   中英

Use a button to load more data from the server without refresh the page

My server load articles from a xml, and send them to my view. I'd like to only send some articles instead, not all of them, and provide to the user a button to load more articles. But how can I send these new data to my view without refreshing the page, is it possible to only update the Model?

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> 

You're going to need to implement some JavaScript to talk to your server via an API. Here's a basic example of getting some different data from a server on each click of the button.

 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> 

This example uses a JSON endpoint; however, you can read values from an XML endpoint by using window.DOMParser inside the .then()

new window.DOMParser()).parseFromString(str, "text/xml")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM