近来因项目须要,须要跨域要求接见数据。跨域接见是指什么?
[跨域]:指的是浏览器不能实行其他网站的剧本。它是由浏览器的同源战略形成的,是浏览器对JavaScript施加的平安限定。所谓同域是指,域名,协定,端口均雷同,不明白没紧要,举个栗子:比方,我的电脑上有2个服务器 192.168.0.11和192.168.0.12。假如第一个服务器上的页面要接见第二个服务器上面的数据,就叫做跨域。或许http://www.baidu.com 要接见www.xxx.com也是差别域名也是跨域。 下面给出完全要求案例:
前端页面要求代码片:
<script type="text/javascript"> function ajaxsubmit(name,phone) { $.ajax({ type: "get", url: "http://10.10.10.132:35709/AppInterface/ResourceInsert.ashx", data: { "share_name": encodeURI(name), "telphone": encodeURI(phone), "fromtype": 4 }, dataType : "jsonp", jsonp: "callback", jsonpCallback: "successcallback", success: function (json) { alert(json.msg); }, error:function(e){ alert("提交失利!请稍后再试"); } }); } </script>
平常处置惩罚程序代码片:
public class ResourceInsert : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; context.Response.ContentEncoding = System.Text.Encoding.UTF8; cms.Model.Resource model = new Model.Resource(); cms.BLL.Resource bll = new BLL.Resource(); //你所须要举行的操纵 model.share_name = HttpUtility.UrlDecode(context.Request["share_name"]); model.ask_telphone = HttpUtility.UrlDecode(context.Request["telphone"]); model.back_row_one = context.Request["fromtype"]; ConvertHelper ch = new ConvertHelper(); model.share_name = ch.RemoveSpecialChar(model.share_name); //successcallback为跨域要求回调函数,牢记必不可少。猎取体式格局也能够为context.Request["callback"], //对应前端页面提议要求的jsonp和jsonpCallback花样为:jsonp_value=jsonpCallback_value if (bll.Exists(model.share_name, model.ask_telphone)) { Message temp = new Message(1, "我们已收到您的要求额!请勿反复提交!", null); context.Response.Write("successcallback" + "(" + JsonConvert.SerializeObject(temp) + ")"); context.Response.End(); return; } else { if (bll.Add(model) > 0) { Message temp = new Message(1, "提交胜利,我们工作人员会尽快复兴你!谢谢关注!", null); context.Response.Write("successcallback" + "(" + JsonConvert.SerializeObject(temp) + ")"); context.Response.End(); return; } else { Message temp = new Message(0, "请确认信息填写无误!", null); context.Response.Write("successcallback" + "(" + JsonConvert.SerializeObject(temp) + ")"); context.Response.End(); return; } } } public bool IsReusable { get { return false; } } }
你认为到这里完了吗?固然没有/斜眼笑。设置文件中固然不能少,web.config文件中的 system.webServer 节点下 增添以下设置:
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer>
以上就是C#中关于ajax跨域接见题目的细致引见的细致内容,更多请关注ki4网别的相干文章!