ajax 访问webservice 跨域
时间: 2023-09-27 13:09:09 浏览: 58
如果你的前端代码和 WebService 部署在不同的域名下,那么就会存在跨域问题。解决跨域问题需要在服务端和前端两个方面进行配置。
服务端配置:
1. 在 WebService 的 `web.config` 文件中增加以下配置:
```xml
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600"/>
</system.web>
```
2. 在 WebService 的代码中增加以下特性:
```csharp
[ScriptService]
public class MyWebService : System.Web.Services.WebService
```
3. 在 WebService 的代码中增加以下方法:
```csharp
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}
```
前端配置:
1. 在前端页面中引入 jQuery 库:
```html
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
```
2. 在前端页面中使用 jQuery 发送 Ajax 请求:
```javascript
$.ajax({
type: "GET",
url: "http://localhost:8080/MyWebService.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d);
},
error: function (response) {
console.log(response.responseText);
}
});
```
注意事项:
1. 服务端必须启用 CORS(跨域资源共享)功能,否则前端请求会被拒绝。
2. 服务端返回的数据必须是 JSON 格式,否则前端无法解析。