jsonp

json获取响应头方法,用于参考,与下面的jsonp无关:

$.ajax({
    type: 'HEAD', // 获取头信息,type=HEAD即可
    url: "http://192.168.2.254/t.html",
    complete: function (xhr, data) {
        // 获取相关Http Response header
        var wpoInfo = {
            // 服务器端时间
            "sessionID": xhr.getResponseHeader('Set-Cookie'),
            "date": xhr.getResponseHeader('Date'),
            // 如果开启了gzip,会返回这个东西
            "contentEncoding": xhr.getResponseHeader('Content-Encoding'),
            // keep-alive ? close?
            "connection": xhr.getResponseHeader('Connection'),
            // 响应长度
            "contentLength": xhr.getResponseHeader('Content-Length'),
            // 服务器类型,apache?lighttpd?
            "server": xhr.getResponseHeader('Server'),
            "vary": xhr.getResponseHeader('Vary'),
            "transferEncoding": xhr.getResponseHeader('Transfer-Encoding'),
            // text/html ? text/xml?
            "contentType": xhr.getResponseHeader('Content-Type'),
            "cacheControl": xhr.getResponseHeader('Cache-Control'),
            // 生命周期?
            "exprires": xhr.getResponseHeader('Exprires'),
            "lastModified": xhr.getResponseHeader('Last-Modified')
        };
        console.log(wpoInfo);
        // 在这里,做想做的事。。。
    }
});

响应过来的编码若与接收的不一致,需设置好渲染编码:

$.ajaxSetup({ scriptCharset: 'utf-8' });


html中JS的写法:

    $.ajaxSetup({ ajaxSettings: { contentType: "application/x-www-form-urlencoded;chartset=gb2312" } });
    $.getJSON("http://192.168.2.254/api/android?callback=?",
    {
        "question": $('li.checked').map(function () { return $(this).text() }).get().join(','),
        "description": $('#area').val(),
        "contact": $('input').val(),
        "device": "android"
    },
    function (data) {  window.android.Tip(JSON.stringify(data));  });

.net服务器jsonp配置(摘自 按MVC jsonp(实验过能用): http://www.25kx.com/art/1908976 ),先实现JsonMediaTypeFormatter类:

using System;
using System.IO; 
using System.Net.Http.Formatting;
using System.Net.Http.Headers; 
using System.Threading.Tasks;
using System.Web;

public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter 
{ 
    private string _callbackQueryParamter; 
    public JsonpMediaTypeFormatter() 
    { 
        SupportedMediaTypes.Add(DefaultMediaType); 
        SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("text/javascript")); 
        MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType)); 
    }
    
    public string CallbackQueryParameter
    { 
        get { return _callbackQueryParamter ?? "callback"; }
        set { _callbackQueryParamter = value; }
    } 
    
    public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
    { 
        string callback;
        if (IsJsonpRequest(out callback))
        { 
            return Task.Factory.StartNew(() => {
                var writer = new StreamWriter(writeStream);
                writer.Write(callback + "("); 
                writer.Flush(); 
                base.WriteToStreamAsync(type, value, writeStream, content, transportContext).Wait();
                writer.Write(")"); 
                writer.Flush(); 
            }); 
        } 
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext); 
    } 
    
    private bool IsJsonpRequest(out string callback)
    { 
        callback = null; 
        switch (HttpContext.Current.Request.HttpMethod) 
        { 
            case "POST": callback = HttpContext.Current.Request.Form[CallbackQueryParameter];  break;
            default: callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter]; break;
        }
        return !string.IsNullOrEmpty(callback); 
    } 

}

在Global.asax的Application_Start()中注册:

GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter()); //set webAPI request return json or jsonp for APP

在WebAPI里写后台程序代码:

    public class APPController : ApiController
    {
        private class Tip
        {
            public bool status { get; set; }
            public string content { get; set; }
        }

        Tip[] tip = new Tip[]{
                new Tip {status = false,content = "服务器出错,请稍候重试!"},
                new Tip {status = true,content = "提交成功!"},
        };
        // api/APP?question=1&description=1&contact=1&device=1
        public HttpResponseMessage Get(string callback ,string question, string description, string contact, string device)
        {         
            try { return Request.CreateResponse(HttpStatusCode.OK,  tip[1]); }
            catch { return Request.CreateResponse(HttpStatusCode.OK, tip[0]); }
        }

        // api/APP?APPuserName=1&APPpwd=1&APPdevice=1
        public HttpResponseMessage Get(string APPuserName, string APPpwd ,string APPdevice)
        {
            try {
                Conn db_conn = new Conn();
                var rs = (from u in db_conn.userInfo.Where(a => a.loginName == APPuserName)
                            join s in db_conn.company on u.userID equals s.userID into s
                            from l in s.DefaultIfEmpty()
                            select new{
                                userID = u.userID,
                                loginName = u.loginName,
                                pwd = u.password,
                                status = u.status,
                                company = l,
                            }).FirstOrDefault();
                if (rs == null) return Request.CreateResponse(HttpStatusCode.OK, new { status = false, content = "用户名不存在!" });
                else if (rs.pwd == Encryption.EncryptString(APPpwd)){
                    LoginManager.Login(new string[] { rs.userID.ToString(), rs.loginName, rs.status, rs.company == null ? null : rs.company.companyID.ToString(), APPdevice, Regex.IsMatch(APPuserName, @"^1[3|4|5|8]\d{9}$") ? APPuserName : null });
                    return Request.CreateResponse(HttpStatusCode.OK, new { status = true, content = Domain.vip });
                }else return Request.CreateResponse(HttpStatusCode.OK, new { status = false, content = "密码错误!" });
            }catch { return Request.CreateResponse(HttpStatusCode.OK, tip[0]); }
        }
     }



参考以下c# .net jsonp:

webForm jsonp应用:http://blog.youkuaiyun.com/donet_expert/article/details/8149694

webForm jsonp(启用cookie):http://www.jb51.net/article/28517.htm

MVC3 jsonp:  http://download.youkuaiyun.com/detail/zxhouyi010101/4885318

webAPI jsonp(需MVC .net4.5)应用:http://www.2cto.com/kf/201312/262552.html

webAPI jsonp(需MVC 未试验)应用:http://weblog.west-wind.com/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+RickStrahl+(Rick+Strahl%27s+WebLog)

MVC jsonp(实验过能用):http://www.25kx.com/art/1908976




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值