fetch()

 

fetch 的功用很像 $.ajax()、XMLHttpRequest()

範例如下

 

Model 的內容為

namespace WebApplication1.Models
{
    public class Person
    {
        public int id { get; set; }
        public string name { get; set; }
    }
}

 

Controller 的內容為

using System.Web.Mvc;
using System.Web.Script.Serialization;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            Person p = new Person() { id = 123, name = "Tom" };

            return Content(ObjectToJSON(p));
        }

        //http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
        private string ObjectToJSON(object obj)
        {
            return new JavaScriptSerializer().Serialize(obj);
        }
    }
}

 

Index.cshtml 的內容為

@{
    ViewBag.Title = "Home Page";
}

<form>
    <button id="btnSend" type="button">送出</button>
</form>

@section scripts{
    <script>
        document.getElementById("btnSend").addEventListener("click", function () {
            let url = 'About';
            let request = {
                method: 'GET',
                cache: 'no-cache',
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            };

            fetch(url, request)
                .then(response => {
                    return response.json();
                })
                .then(model => {
                    console.log(model.id);
                    console.log(model.name);
                })
                .catch(error => {
                    console.error(error);
                });
        });
    </script>
}

 

執行結果為

 

參考資料:

Using Fetch

AJAX與Fetch API

Response