Js C# 实现跨域访问数据

使用项目一的js调用项目二的数据

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',//数据类型必须是jsonp
17                 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 }
控制器代码
原文地址:https://www.cnblogs.com/liuph/p/4168738.html