1. 程式人生 > >前端跨域之Jsonp實現原理及.Net下Jsonp的實現

前端跨域之Jsonp實現原理及.Net下Jsonp的實現

ali action query localhost info col 分享圖片 ice head

jsonp的本質是通過script標簽的src屬性請求到服務端,拿到到服務端返回的數據 ,因為src是可以跨域的。前端通過src發送跨域請求時在請求的url帶上回調函數,服務端收到請求時,接受前端傳過來的回掉函數名稱,將其拼接成js函數調用返回到前端即可完成跨域請求。

前端實現代碼:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> </html> <script> function successFun(data) { console.log(data); } function show(data) { console.log(data); }
</script> <!-- 把請求的成功的回掉函數名稱通過url傳參傳到服務端,服務端返回時需要拼接一個函數調用返回到前端 --> <script src="https://localhost:44381/Home/Action?cb=show"></script> <script src="https://localhost:44381/Home/GetScript?cb=successFun"></script>

.Net服務端代碼:

using System.Collections.Generic;
using
Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Jsonp.Controllers { public class HomeController : Controller { public IActionResult Action() { var cb = Request.Query["cb"]; return Content(cb + "(123)"); } public IActionResult GetScript() { var cb = Request.Query["cb"]; var data = new List<int>() { 1,2,3,4,5,6,8,9,6,3,5,2,0,3 }; var result = $"{cb}({JsonConvert.SerializeObject(data)})"; return Content(result); } } }

技術分享圖片

技術分享圖片

前端跨域之Jsonp實現原理及.Net下Jsonp的實現