標籤:style blog http ar io color os sp on
1.
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" />10 <title>js跨域調用</title>11 <script src="~/Scripts/jquery-1.8.2.min.js"></script>12 <script>13 $(function () {14 $.ajax({15 type: "GET",//必須是GET方式16 dataType: ‘jsonp‘,//資料類型必須是jsonp17 jsonp: ‘jsonp_callback‘,18 url: ‘http://localhost:14373/test/GetString?callback=?‘,//必須有?callback=? 名字可以換19 success: function (da) {20 $("#name").html(da.name);21 $("#value").html(da.value);22 }, error: function () {23 alert("ERROR");24 }25 });26 });27 </script>28 </head>29 <body>30 <span id="name"></span>31 <span id="value"></span>32 </body>33 </html>
HTML代碼
2.
1 using System; 2 using System.Web.Mvc; 3 4 namespace MVC4.Controllers 5 { 6 public class testController : Controller 7 { 8 public ActionResult Index() 9 {10 return View();11 }12 13 public void GetString()14 {15 var response = HttpContext.Response;16 response.ContentType = "text/json";17 string str = Request.QueryString["callback"];//JS接受變數名18 response.Write(str + "({\"name\":" + "\"" + "姓名" + "\"" + ",\"value\":" + "\"" +"值"+ "\"})");//返回資料19 }20 }21 }
控制器代碼
C#js跨域調用