ajax 跨域
一个一般处理程序服务端
返回的数据是json
public void ProcessRequest(HttpContext context) { citys c = new citys(); c.age = "12"; c.city = "bj"; c.hosst = "www.baidu.com"; c.name = "张三"; c.weather = "天气";
string cc = JsonConvert.SerializeObject(c); context.Response.ContentType = "text/plain"; context.Response.Write( cc ); }
这个一般处理程序返回jsonp
public void ProcessRequest(HttpContext context) { citys c = new citys(); c.age = "12"; c.city = "bj"; c.hosst = "www.baidu.com"; c.name = "张三"; c.weather = "天气"; string cc = JsonConvert.SerializeObject(c); context.Response.ContentType = "text/plain"; string callbackFunName = context.Request["callback"]; context.Response.Write(callbackFunName + "([" + cc + "])"); }
可以看出jsonp是包裹着json这样理解
json:cc
jsonp:callbackFunName(cc)
下面是客户端的请求
$("#aaa").click(function () { $.ajax({ type: "get", async: false, url: "http://www.server.com/handler1.ashx", dataType: "jsonp", jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback) jsonpCallback: "success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名 success: function (data) { alert(data); alert(data[0].name); }, error: function () { alert('fail'); } }); });
---------------------------------------------------------------------------------------------------------------------------------------------------
自己做一个一般处理程序,让请求变为同域
一个天气请求的接口处理
public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write(getString()); } private string getString() { HttpWebRequest re = WebRequest.Create("http://www.weather.com.cn/data/sk/101010100.html") as HttpWebRequest; HttpWebResponse rs = re.GetResponse() as HttpWebResponse; string st = new StreamReader(rs.GetResponseStream()).ReadToEnd(); return st; } public bool IsReusable { get { return false; } } }
使用ajax 请求变成了同域,
返回的数据为string ,使用JSON.parse() 转化为json 对象
直接使用js对象 就可以查询想看的数据了
<script> $("#aaa").click(function () { debugger; $.ajax({ type: "get", async: false, url: "handler1.ashx", success: function (data) { debugger; alert(data); debugger; var js = JSON.parse(data); var v = js.weatherinfo.city; var d = js.weatherinfo.temp; var a = js.weatherinfo.WD; alert(js.city); }, error: function () { alert('fail'); } }); }); </script>