如何使用Fetch API在JavaScript与C#之间传递数据?
使用Fetch API实现JavaScript与C# WebService的数据交互
嘿,既然你已经搞定了Ajax的方式,那切换到Fetch API其实非常顺畅,我来帮你把代码补全并拆解关键要点~
第一步:修正C# WebService代码
你的WebService代码里有个关键注释必须解开,[ScriptService]特性是让WebService支持接收客户端JSON请求并返回对应响应的核心,否则Fetch请求会直接失败。修正后的代码如下:
namespace WebApplication1 { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] // 必须解开这个注释! public class WebService1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } // 额外加一个带参数的示例方法,方便演示POST传参 [WebMethod] public string GreetUser(string username) { return $"Hello, {username}!"; } } }
第二步:Fetch API的GET请求示例
先实现调用HelloWorld方法的GET请求,Fetch基于Promise的写法比Ajax更简洁直观:
// 调用HelloWorld的GET请求 fetch('http://localhost:62177/WebService1.asmx/HelloWorld') .then(response => { // Fetch不会自动抛出HTTP错误(比如404/500),得手动检查状态 if (!response.ok) { throw new Error(`请求失败!状态码: ${response.status}`); } // ASMX默认返回XML格式,先转成文本再解析 return response.text(); }) .then(xmlText => { // 从XML中提取返回的字符串结果 const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "text/xml"); const result = xmlDoc.getElementsByTagName("string")[0].textContent; console.log(result); // 输出: Hello World }) .catch(error => { console.error('请求出错:', error); });
第三步:Fetch API的POST请求示例(传递参数)
如果需要给WebService传参数,就用POST请求,注意要设置正确的请求头和参数格式:
// 准备要传递的参数 const userData = { username: "Epulari" }; fetch('http://localhost:62177/WebService1.asmx/GreetUser', { method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8', }, // 把参数对象转成JSON字符串 body: JSON.stringify(userData) }) .then(response => { if (!response.ok) { throw new Error(`请求失败!状态码: ${response.status}`); } return response.text(); }) .then(xmlText => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "text/xml"); const result = xmlDoc.getElementsByTagName("string")[0].textContent; console.log(result); // 输出: Hello, Epulari! }) .catch(error => { console.error('请求出错:', error); });
实用小技巧
- 改成JSON响应:如果不想解析XML,可以给WebMethod加
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]特性,这样就能直接用response.json()处理返回结果,不用再写XML解析的代码。 - 跨域处理:如果前端和WebService不在同一个域名下,需要给WebService配置CORS(可以通过NuGet安装CORS包,或者手动添加HTTP响应头)。
- async/await简化写法:Fetch支持async/await,能把Promise的链式调用改成更像同步代码的写法,可读性更高。
内容的提问来源于stack exchange,提问作者Epulari
相关产品推荐
相关产品推荐

