Js C# 实现跨域访问数据

时间:2023-03-09 16:27:16
Js C# 实现跨域访问数据

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

1.项目一

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>js跨域调用</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",//必须是GET方式
dataType: 'jsonp',//数据类型必须是jsonp
jsonp: 'jsonp_callback',
url: 'http://localhost:14373/test/GetString?callback=?',//必须有?callback=? 名字可以换
success: function (da) {
$("#name").html(da.name);
$("#value").html(da.value);
}, error: function () {
alert("ERROR");
}
});
});
</script>
</head>
<body>
<span id="name"></span>
<span id="value"></span>
</body>
</html>

HTML代码

2.项目二

 using System;
using System.Web.Mvc; namespace MVC4.Controllers
{
public class testController : Controller
{
public ActionResult Index()
{
return View();
} public void GetString()
{
var response = HttpContext.Response;
response.ContentType = "text/json";
string str = Request.QueryString["callback"];//JS接受变量名
response.Write(str + "({\"name\":" + "\"" + "姓名" + "\"" + ",\"value\":" + "\"" +"值"+ "\"})");//返回数据
}
}
}

控制器代码