ASP.NET ashx文件方法如何支持跨域请求

ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。

即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。

官方问题说明:

“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.

 

如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。

 

因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。

 

例如:客户端的域名是www.client.com,而请求的域名是www.server.com

如果直接使用ajax访问,会有以下错误

XMLHttpRequest cannot load http://www.server.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.

 

ashx告诉浏览器对于跨域访问不要拦截返回值,允许客户端获得响应:

context.Response.AddHeader("Access-Control-Allow-Origin", "*");

 例如对于jQuery for ajax,就是在第一行代码声明一次:

 

jQuery.support.cors = true;

 

 

关于JavaScript跨域问题及实时刷新解决方案

转载  发布时间:2014年06月09日 09:01:32   作者:    我要评论

 
在页面显示其他网站上面的数据,需要用Ajax,就涉及到跨域问题,下面有个示例,大家可以看看
 
在自己页面显示其他网站上面的数据,需要用Ajax,就涉及到跨域问题, 

解决方案:jQuery.support.cors = true; (浏览器支持跨域访问), 

实例: 
 

//浏览器支持跨域访问 

var stuid = $("#stuid").val();
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://XXX.COM/student/Proc.ashx?action=add",
data: { stuid: stuid, sex: "男" },
dataType: "json",
success: function (data) {
alert(data.d);
$("#show").text("").text(stuid +"登记成功")
}
});

//每60000毫秒/1分钟调用GetValue()方法。 
setTimeout("GetValue()", 60000); 
 
ptschool.ptschoolEntities db = new ptschool.ptschoolEntities();
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Charset = "utf-8";
        context.Response.AddHeader("Access-Control-Allow-Origin", "*");
        
        string action = context.Request["action"];
        switch (action)
        {
            case "add":
                //上传附件
                add(context);
                break;
            case "leave":
                //上传附件
                leave(context);
                break;
        }
        context.Response.End();
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="context"></param>
    private void add(HttpContext context)
    {
        string stuid = context.Request.Form["stuid"];
        string stuIMG = context.Request.Form["stuimg"];
        if (string.IsNullOrEmpty(stuid) != true)
        {
            T_StudentLogin astu = new T_StudentLogin();
            astu.StuId = stuid;
            astu.StuImg = stuIMG;
            astu.AddTime =astu.LoginTime = System.DateTime.Now;
            db.AddToT_StudentLogin(astu);
            db.SaveChanges();
            context.Response.Write("成功!");
        }
        else
        {
            context.Response.Write("失败!");
        }
    }

 

 
posted @ 2018-06-03 19:51  becket  阅读(1328)  评论(0编辑  收藏  举报