JQuery和原生JS跨域加载JSON数据或HTML。

前提:有时候需要在网页上,加载另一个网站上的数据。或者加载另一个网站上的一个页面。Js的Ajax请求不具备跨域功能,可以使用JQuery来实现。

网页端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);
        }
    });
});

服务端代码:

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string html = string.Empty;
            using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "/temppage.html", FileMode.OpenOrCreate))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    html = sr.ReadToEnd();
                }
            }
            
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Jsonp jsp = new Jsonp();
            jsp.html = html;
            string json = jss.Serialize(jsp);
            //这里需要注意的是,JSONP要返回的并不是标准的JSON格式,而是下面这样的一个格式
            //callbackname(json)  其中callbackname是从JS端传来的参数。json是JSON数据,括号也不能少。
            string callback = context.Request["callback"];
            context.Response.Write(callback + "(" + json + ")");

        }
        public class Jsonp
        {
            public string html { get; set; }
            public string selector = "body";
        }
//原生JS跨域方法

var script = document.createElement("script");

script.src = "http://192.168.1.145:8089/AdSource/D?ad;

document.head.appendChild(script);

function lian_adv_writer(data) {

alert(data);

}