jsonp实现方法

jsonp实现:

  1. 在不引入jQuery等封装了jsonp功能框架的情况下实现;
  2. html页面里要有以下要点:
    -. 定义一个函数对象(CallBackFun,函数对象名称下面要用的),用于jsonp从服务器获取到数据后的处理;
	<script>
		var CallBackFun=function(data){
			$("#data-jsonp").html("数据: " +JSON.stringify(data.value));
		}
	</script>

-. 比如通过按钮点击事件,动态生成script标签并设置src属性为服务端接口,参数要有函数对象名称,其他可选参数根据实际情况需要添加;

	  document.getElementById('jsonp').onclick=function () {
				var url='http://localhost:5000/values/GetJsonp?callBack=CallBackFun&id=2'
				var script= document.createElement('script')
				script.setAttribute('src',url)
				document.getElementsByTagName('body')[0].appendChild(script)
            };
  1. 服务端接口(用c#实现),参数要接受一个函数名,其他可选参数根据实际情况需要添加,与上一步的script标签的src属性的url参数保持对应;
  2. 服务端接口生成数据后,字符串拼接成js函数对象的样子,CallBackFun(数据对象);
        [HttpGet]
        [Route("GetJsonp")]
        public void Getjsonp(string callBack, int id=1)
        {
            var o = new Advertisement[]{
                new Advertisement{ Id=1,Title="张三"},
                new Advertisement{ Id=2,Title="andy"},
                new Advertisement{ Id=3,Title="three"}
            };

            var str = JsonConvert.SerializeObject(o.Where(o => o.Id == id));
            //重要,一定要这么写
            string response = string.Format(""value":"{0}"", str);
            string call = callBack + "({" + response + "})";
            string re= call.Replace(""[", "[").Replace("]"", "]");
            Response.WriteAsync(re);
        }
  1. 点击按钮后,html页面会动态的生成script标签,并通过src属性,访问了服务器接口,服务器接口拼接js函数返回给html端,html端收到后执行这个js函数,按第一步的函数定义解析出数据;
原文地址:https://www.cnblogs.com/zoulei0718/p/14315566.html