js调用问题
最近用js调用另一个站点时报错了,报错信息:No 'Access-Control-Allow-Origin' header is present on the requested resource。js跨域问题。
后台C#接口
使用默认的回调函数:
public class DemoController : ApiController { [Route("~/demo")] [HttpGet] public HttpResponseMessage Demo(int OrderId) //C#传参数不区分大小写 { HttpResponseMessage response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(String.Format("callbackFun({0})", (new { IsSuccess = "-1000", Msg = "resp.Msg" }).ToJson())); return response; } }
前台js调用示例:(回调函数和后台指定一致,可以不申明function callbackFun(data)函数,默认success函数会被调用;如果申明了callbackFun函数,会先调callbackFun,然后再调success函数)
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery</title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> function b_click(){ $.ajax({ type:"GET", async:false, dataType: 'jsonp', //跨域调用 jsonpCallback: "callbackFun", //指定回调函数名称 data: {"orderId":4811}, //timeout: 5000, //超时设置 //contentType: "application/json;utf-8", url:"http://ab.test.com/demo", success:function(result){ console.log("success"); console.log(result); alert(result.Msg); }, error:function(result){ console.log("fail"); console.log(result); alert(result.Msg); } }); //function callbackFun(data){ //console.log("call"); //} } </script> </head> <body data-spy="scroll" data-target=".navbar-example"> <input type="button" value="click me!" onclick="b_click();" /> </body> </html>
浏览器看js请求链接:http://ab.test.com/demo?callback=callbackFun&orderId=4811
可以看出:如果不指定回调参数名称,默认是callback
指定回调函数名:
服务端接口:
public class DemoController : ApiController { [Route("~/demo")] [HttpGet] public HttpResponseMessage DemoCheck(int OrderId, String callbackMethod) { HttpResponseMessage response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(String.Format(callbackMethod + "({0})", (new { IsSuccess = "-1000", Msg = "resp.Msg" }).ToJson())); return response; } }
接口返回结果:
指定回调参数名和值:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery</title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> function b_click(){ $.ajax({ type:"POST", async:false, dataType: 'jsonp',
//jsonp的值自定义,如果使用callbackMethod,那么服务器端,要返回一个callbackMethod的值对应的对象. jsonp: 'callbackMethod', jsonpCallback: "callbackFun", //指定回调函数名称 data: {"orderId":4811}, //timeout: 5000, //contentType: "application/json;utf-8", url:"http://ab.test.com/demo", success:function(result){ console.log("success"); console.log(result); alert(result.Msg); }, error:function(result){ console.log("fail"); console.log(result); alert(result.Msg); } }); } </script> </head> <body data-spy="scroll" data-target=".navbar-example"> <input type="button" value="click me!" onclick="b_click();" /> </body> </html>
请求url:http://ab.test.com/demo?callbackMethod=callbackFun&orderId=4811