关于这个 jQuery Ajax跨域访问 WebService 前天整了好几个小时没整明白
今天再看一下 结果突然就顿悟了
1.建一个空webApplication --添加--新建项--web服务(asmx)[微软这命名挺有意思的 ashx aspx asmx 0.0为什么不是ms开头呢 估计还是历史问题谁叫以前有个asp呢 知道原因的 可以和我说一下]
去掉有关的注释
![](https://img-blog.csdnimg.cn/img_convert/b0a8cc69cd46c6fe1c5849dc901a35a2.gif)
![](https://img-blog.csdnimg.cn/img_convert/52e6b6d0229b6dcc9be902312723b3c8.gif)
namespace WebServiceTest
{
/// <summary>
/// JsAccess 的摘要说明
/// </summary>
[WebService(Namespace = "http://localhost:51811")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]//这里原来有注释的 现在去掉
public class JsAccess : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
2 f5一下 运行的端口记录一下 我的是这样的
3 写个html页面 引用一下 jQuery
![](https://img-blog.csdnimg.cn/img_convert/a2f20fcb62359e1ec0ce45913ff643e5.gif)
![](https://img-blog.csdnimg.cn/img_convert/d11fb488b20f94982bd2248ffa034c6b.gif)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function(){
$("#ButtonNO").click(function () {
alert(123);
var options = {
type: "POST",
url: "http://localhost:51811/JsAccess.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
}
$.ajax(options)
})
})
</script>
<body>
<button id="ButtonNO"> go</button>
</body>
</html>
4.这个是最重要的,虽然很简单,但对没用过.net的人来说还是很难的,比如我。这个网上有说明,可是前天就是没整对。
修改 WebApplication 的 web.config 的system.web节点 和 system.webServer这两个节点出 出自 https://www.cnblogs.com/jianfengcai/p/6253330.html
需要在web.config的configuration节点中加入如下的黑体部分内容 这里边两个节点应是存在的 vs2015有是有的 我前天就以为没有,给多加了一个system.webServer节点,
改时先确认没有再修改
<system.web> <webServices> <protocols> <add name="HttpGet" /> <add name="HttpPost" /> </protocols> </webServices>
</system.web>
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" /> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type" /> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol>
</system.webServer>
ok这样 通过浏览html 不要关掉vs的调试 点击 go 按钮 就可以看到效果了
这webservice 里的 Namespace 好像没用的样子 随便给个就可以了 可能网上有用 大约是为了唯一标识
最后我觉的,学习就这样:你有不会的问题 ,去网上找 ,找到了也调出来了,那么你就总结一下,到得出自己的结论再把他写下来,尽量不要拷贝别人的,哪怕你写的和别人的一样,也别只是收藏,自己写一写总结,总是有帮助的,还能加深记忆。