ajax跨域请求调用
1.WebService 接口编写
步骤:新建web项目=》添加web service=》编写方法接口=》然后发布(本地测试可以直接把这个web service运行起来)。
关键如何让外部Ajax 调用。
首先,配置WebService 项目配置文件(web.config)红色部分必须配置,这样第三方才能调用接口方法(经测试通过,直接粘贴就ok),不懂可以百度。
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.0" />
</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>
</configuration>
2、其次,这里贴出WebService 中代码部分,这里我自定义一个返回一个Person集合GetPersonList(),可供Ajax调用。
(1)发布时需要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布以后的域名地址。当然本地测试使用localhost就可以或者使用默认的即可。
(2)要放开[System.Web.Script.Services.ScriptService] 的注释。
以上两步做到写接口发布WebService,访问http://192.168.1.90:5555/XXX.asmx 地址。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace MyWebService
{
/// <summary>
/// MyWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://localhost:47737/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public int Add(int num1,int num2)
{
return num1 + num2;
}
}
}
3.第三方Ajax调用。
$.ajax({
url: "http://localhost:47737/MyWebService.asmx/Add",
type: "post",
data: "{ 'num1': 2,'num2': 5 }",
contentType: "application/json",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function () {
alert("发送ajax请求失败!");
}
});


浙公网安备 33010602011771号