最近做项目,需要跨域请求访问数据问题。下面通过本文给大家分享c#中ajax跨域访问代码详解,需要的朋友可以参考下
最近因项目需要,需要跨域请求访问数据。跨域访问是指什么?
[跨域]:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对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跨域访问问题的详细介绍的详细内容。