首页 技术 正文
技术 2022年11月14日
0 收藏 499 点赞 4,977 浏览 1438 个字

利用jsonp进行跨域请求资源

C# MVC ApiControllers准备如下:

1、需要在引用处右键管理NuGet安装jsonp插件

2、在Application_Start()中配置

GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));

3、在ApiControllers中写服务端接口代码

 [HttpGet]
public void H5PlusTextJsAjax( string callback = "")
{

         HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Origin”, “*”);

            HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
List<ReturnJosn> callbackjson = new List<ReturnJosn>();
callbackjson.Add( new ReturnJosn() { name = "fhjson" });
HttpContext.Current.Response.
Write(HttpContext.Current.Request.Params["callbackparam"].ToString() +
"(" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(callbackjson) + ")");
HttpContext.Current.Response.End();
//return HttpContext.Current.Request.Params["callbackparam"].ToString() +
// "(" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(callbackjson) + ")";
}

4、在其他页面写前台代码

$.ajax({
type : "get",
async:false,
url : "http://localhost:11462/api/RePass",
dataType : "jsonp",
data:"{}",
jsonp: "callbackparam",//服务端用于接收callback调用的function名的参数 success : function(json){ alert(json[0].name);
},
error:function(httpstatesss,b11,c111){
alert('fail');
}
});

  

测试成功。需要注意apicontrollers中写入返回流文本的json字符串一定要包含jq callback的随机名字JQuerxxxxxx(你的json字符串)。不然你的请求success但是会进入error里面。jq解析json不成功会抛出parseerror。”jQuery191002365952031686902_1436757310853 was not called”

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294