ajax 访问web api


/**
* @描述:公共方法库
*/
var AjaxUtils = {
    //服务器地址
    APIUrl: 'http://localhost:58888/',
    /**
     * @描述:请求接口地址
     */
    Controller: {
        SysEmployee: 'api/Employee/'
        , StockInventoryBill: 'api/StockInventoryBill/'
        , Session: 'api/SysSession/'
    },
    /**
    * @描述:Post请求webapi服务
    * 为解决post请求时参数 问题 所以将参数对象 以字符串形式拼接以url后台请求服务
    */
    PostApiService: function (para) {
        var serviceObject = {
            type: 'post',
            showloadingFlag: false,
            async: true,
            loadingmsg: '努力处理中,请稍等……',
            para: {},
            success: function (dataJson) { },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        };
        //合并参数
        $.extend(serviceObject, para);
        console.log('serviceObject', serviceObject)
        //请求地址
        var remoteUrl = AjaxUtils.APIUrl + serviceObject.controller + serviceObject.method;
        //支持跨域访问
        jQuery.support.cors = true;
        $.ajax({
            type: "post",
            async: serviceObject.async,
            url: remoteUrl,
            contentType: "application/json",
            data: JSON.stringify(serviceObject.para),
            beforeSend: function (XHR) {
                //发送ajax请求之前向http的head里面加入验证信息
                var userInfo = UserUtils.GetUserInfo();
                console.warn(userInfo);
                if (userInfo != undefined) {
                    XHR.setRequestHeader('Authorization', 'Bearer ' + userInfo.FToken);
                }
                console.log(serviceObject.controller + serviceObject.method + '=>beforeSend=>>', JSON.stringify(XHR))
            },
            success: function (data) {
                console.log(serviceObject.controller + serviceObject.method + '=>successJson=>>', data)
                //var dataJson = JSON.parse(data)
                serviceObject.success(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var errJson = { Request: XMLHttpRequest, Status: textStatus, Thrown: errorThrown };
                console.error(serviceObject.controller + serviceObject.method + '=>errJson=>>', errJson)
                serviceObject.error(XMLHttpRequest, textStatus, errorThrown);
                //系统启用 服务器端ticket验证后
                //如果验证不通过给出用户提示  当前帐号已在其它终端登陆,请重新登陆
                //默认此值 为false 没有弹出提示消息 
                switch (parseInt(XMLHttpRequest.status)) {
                    case 401:
                        alert('responseStatus' + XMLHttpRequest.status)
                        break;
                    case 403:
                        alert('responseStatus' + XMLHttpRequest.status)
                        break;
                }
            },
            complete: function () {
            }
        });
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTTP 405错误通常发生在使用Ajax调用Web API时,这是因为Web API默认情况下只支持GET和POST请求,而不支持PUT、DELETE、OPTIONS等请求方法。解决这个问题的方法是在Web API端添加一个处理OPTIONS请求的方法。 在Web API中,可以使用Web API的CORS功能来解决这个问题。CORS(跨域资源共享)是一种Web标准,允许在不同域名下的浏览器访问服务器资源。 为了启用CORS,需要在Web API项目中安装Microsoft.AspNet.WebApi.Cors NuGet包。然后,在WebApiConfig类中启用CORS: ``` using System.Web.Http; using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 启用CORS var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // ...其他配置 } } ``` 这里的“*”表示允许任何域名、任何方法、任何标头访问Web API。你也可以指定具体的域名、方法和标头。 在客户端使用Ajax时,需要设置withCredentials为true,这样才能在跨域请求时发送Cookies和认证信息。例如: ``` $.ajax({ type: "POST", url: "http://example.com/api/resource", data: JSON.stringify({data: "hello"}), contentType: "application/json", xhrFields: { withCredentials: true }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.log(xhr.responseText); } }); ``` 在这个例子中,我们向http://example.com/api/resource发送一个带有数据的POST请求,并设置withCredentials为true,以便发送Cookies和认证信息。如果请求成功,我们将收到响应数据,并将其打印到控制台中。如果请求失败,我们将打印xhr.responseText,这包含了服务器返回的错误信息。 希望这个解决方案可以帮助你解决问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值