ajax调用C# webapi接口

js ajax请求代码:

$.ajax({
        // url: 'http://192.168.83.51:8025/handler/AutoDifferenceService.ashx',
        url: requestUrl,
        data: { 'cmd': 'autodifference', 'batchid': this.batchid },//传参
        dataType: 'jsonp',
        jsonp: 'jsonpcallback',
        jsonpCallback: 'jsonpFn',//跨域访问
        type: 'GET', // 类型
        timeout: 100000, // 超时
        // 请求成功
        success: function(data, status) {
        	console.log(data)
        },
        // 失败/超时
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          console.log(textStatus)
        },
        success_jsonpCallback: function(data) {
          console.log(data)
        }
      })
      
function success_jsonpCallback(data) {
      alert('测试成功')
    },

webapi代码:

public void ProcessRequest(HttpContext context)
        {
            try
            {
                string returnData = string.Empty; //返回数据
                string cmd = context.Request.Params["cmd"]; //获得命令指令
                if (!string.IsNullOrEmpty(cmd))
                {
                    switch (cmd)
                    {
                        case "autodifference":
                            var entity = new AutoDifferenceEntity();
                            string batchid = context.Request.Params["batchid"].ToString();
                            int intResult = entity.AutoDifference(batchid, pictureid, type, picindex, strUserName);
                            entity.code = intResult.ToString();
                            returnData = JsonHelper.ObjectToJSON(entity);
                            string jsonp = context.Request["jsonpcallback"];
                            returnData = jsonp + "(" + returnData + ")";
                            break;
                    }
                }
                context.Response.ContentType = "application/json";
                context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                context.Response.Write(returnData);
                context.Response.AddHeader("Access-Control-Allow-Origin", "*");//跨域访问
            }
            catch (Exception exc)
            {
                context.Response.Write(exc);
            }
        }

你可能感兴趣的:(JavaScript)