JS跨域ajax访问
2023-09-14 08:57:06 时间
方式1:jsonp解决跨域访问
需要服务和js配合
服务
[WebMethod] public void HelloWorld2(string name) { HttpContext.Current.Response.ContentType = "application/json;charset=utf-8"; string jsonCallBackFunName = string.Empty; jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString(); HttpContext.Current.Response.Write(jsonCallBackFunName + "({ \"Result\": \"Helloword2" + name + "\" })"); }
JS调用
var dataStr = "name=" + $("#birthday").val(); $.ajax({ type: "post", url: "http://192.168.0.99:8082/WebService1.asmx/HelloWorld", dataType: "jsonp", jsonp: 'jsoncallback', contentType: "application/jsonp;charset=utf-8", data: dataStr, success: function (result) { //返回结果 alert(result.Result); $("#name").val(result.Result); }, error: function (e) { window.alert(e.status); } }); });
方式2:增加配置处理跨域
如果是在.net下则在web.config中增加配置
在system.webServer下增加可跨域访问
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /> </customHeaders> </httpProtocol>
如果是调用webservice在服务端config中增加配置在system.web下增加
<protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="Documentation"/> </protocols>
服务
[WebMethod] public string HelloWorld1(string name) { return "{data:你好:" + name + "}"; }
前台调用方式
$.ajax({ type: "post", url: "http://192.168.0.99:8082/WebService1.asmx/HelloWorld", dataType: "json", data: "{name:'" + birthday + "'}",//参数 contentType: "application/json;charset=utf-8", success: function (result) { //返回结果 $("#name").val(result.d); }, error: function (e) { window.alert(e.status); } }); });
相关文章
- ajax跨域问题以及解决方案_js跨域请求的三种方法
- ajax实现跨域_js跨域请求的三种方法
- JS字符串的不可变性
- Ajax教程_ajax是服务器端动态网页技术
- js定时器与延时器_JS做定时器倒计时
- spring ajax 长轮询,Ajax轮询和长轮询
- Vue.js 学习笔记 - 组件(Components)
- Node.js REPL模块
- 【JS 逆向百例】猿人学系列 web 比赛第五题:js 混淆 - 乱码增强,详细剖析
- 【JS 逆向百例】猿人学系列 web 比赛第二题:js 混淆 - 动态 cookie,详细剖析
- js判断checkbox复选框是否被选中的方法
- JS动态引入js、CSS动态创建script/link/style标签详解编程语言
- Js+Dhtml:WEB程序员简易开发工具包(预先体验版)
- js函数般调用正则
- JQuery,Extjs,YUI,Prototype,Dojo等JS框架的区别和应用场景简述
- js图片放大效果修正版
- js下通过getList函数实现分页效果的代码
- JS.GetAllChild(element,deep,condition)使用介绍
- JS实现模仿微博发布效果实例代码
- js获取当前地址JS获取当前URL的示例代码
- Ajax局部更新导致JS事件重复触发问题的解决方法