JQuery和原生JS跨域加载JSON数据或HTML。
2014-05-31 16:26
363 查看
前提:有时候需要在网页上,加载另一个网站上的数据。或者加载另一个网站上的一个页面。Js的Ajax请求不具备跨域功能,可以使用JQuery来实现。
网页端JS代码:
服务端代码:
varscript=document.createElement("script");
script.src="http://192.168.1.145:8089/AdSource/D?adid="+advid+"&callback=lian_adv_writer";
script.type="text/javascript";
document.head.appendChild(script);
functionlian_adv_writer(data){
alert(data);
}
网页端JS代码:
$(function(){ $.ajax({ type:"get", async:false, url:"http://localhost:13964/getpage.ashx?callback=?",//服务端URL,该URL返回一段JS数据。如需返回HTML,只需把HTML组织成JSON即可,比如{"html":"<html></html>"} dataType:"jsonp",//表示该请求为跨域的JSOP请求 jsonp:"htmlcall",//作用未知。随便填,但也能正常执行 jsonpCallback:"htmlcallback",//该值会把URL中的callback参数值替换,比如会把callback=?替换成callback=htmlcallback success:function(json){ $(json.selector).append(json.html); }, error:function(XMLHttpRequest,textStatus,errorThrown){ alert('fail'); alert(textStatus); alert(errorThrown); } }); });
服务端代码:
publicvoidProcessRequest(HttpContextcontext) { context.Response.ContentType="text/plain"; stringhtml=string.Empty; using(FileStreamfs=newFileStream(AppDomain.CurrentDomain.BaseDirectory+"/temppage.html",FileMode.OpenOrCreate)) { using(StreamReadersr=newStreamReader(fs)) { html=sr.ReadToEnd(); } } JavaScriptSerializerjss=newJavaScriptSerializer(); Jsonpjsp=newJsonp(); jsp.html=html; stringjson=jss.Serialize(jsp); //这里需要注意的是,JSONP要返回的并不是标准的JSON格式,而是下面这样的一个格式 //callbackname(json)其中callbackname是从JS端传来的参数。json是JSON数据,括号也不能少。 stringcallback=context.Request["callback"]; context.Response.Write(callback+"("+json+")"); } publicclassJsonp { publicstringhtml{get;set;} publicstringselector="body"; } //原生JS跨域方法
varscript=document.createElement("script");
script.src="http://192.168.1.145:8089/AdSource/D?adid="+advid+"&callback=lian_adv_writer";
script.type="text/javascript";
document.head.appendChild(script);
functionlian_adv_writer(data){
alert(data);
}
相关文章推荐
- html中通过js获取接口JSON格式数据解析以及跨域问题
- html中通过JS获取JSON数据并加载的方法
- [转]IE9.0或者360下js(JavaScript、jQuery)不能正确执行(加载),按F12后执行正常;Firefox下ajax的success返回数据data(json、string)无法获取
- html中通过js获取接口JSON格式数据解析以及跨域问题
- 原生js,jquery通过ajax获得后台json数据动态新增页面元素
- IE9.0或者360下js(JavaScript、jQuery)不能正确执行(加载),按F12后执行正常;Firefox下ajax的success返回数据data(json、string)无法获取
- AJAX 原生js以及Jquery解析html,xml,txt,json格式文本
- 使用jQuery或者原生js实现鼠标滚动加载页面新数据
- IE9.0或者360下js(JavaScript、jQuery)不能正确执行(加载),按F12后执行正常;Firefox下ajax的success返回数据data(json、string)无法获取
- Ajax解析html、xml、json、js原生方式、jquery方式
- 使用jQuery或者原生js实现鼠标滚动加载页面新数据
- 基于jQuery的AJAX和JSON实现纯html数据模板
- JQuery使用getJSON跨域调用数据
- jquery随记----ajax基于请求加载数据(追加html)
- 这大半天就耗在一个jQuery跨域Json上了——jQuery跨域获取json数据总结
- [jQuery插件开发][dynamicTable2.0]根据JSON数据自动生成HTML Table
- JQuery使用getJSON跨域调用数据
- 基于jQuery的AJAX和JSON实现纯html数据模板
- Json2Template.js 基于jquery的插件 绑定JavaScript对象到Html模板中
- 使用jQuery的getJson进行跨域提取数据