html Js跨域提交数据方法,跨域提交数据后台获取不到数据
MVC实现方式:(后台获取不到方法请参考下面js)
[ActionAllowOrigin]
[HttpPost]
public JsonResult Cooperation()
{
return json();
}
在方法前面加上[ActionAllowOrigin] 这个方法是自定义的继承自AuthorizeAttribute
public class ActionAllowOriginAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
var origin = filterContext.HttpContext.Request.Headers["Origin"];
filterContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin",origin);
}
}
这样就支持跨域了;调用方法如下:(如果后台获取不到方法的话请复制本js)
function test()
{
$.ajax({
url: "http://www.baidu.com/TieBa/AddImgs",//这里是提交url
type: "post",
// dataType: "json",
data: {name:$("#Name").val(),Phone:$("#Phone").val()},
success: function (msg) {
console.log(msg)
}
}
//问题:
如果遇到浏览器不支持的话就把origin换成*号 如下:
filterContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin","*");