ASP.NET C#后端如何向jQuery AJAX发送字符串并完成解析
问题修复方案
核心错误说明
- 后端WebMethod存在拼写错误、调用逻辑错误,前端AJAX请求的参数、回调、返回值处理均存在问题
- 先纠正逻辑误区:ASP.NET的
[WebMethod]是供前端AJAX主动调用的接口,你在后端openFile方法里直接调用sendString无法把值推送到前端,必须由前端发起请求后,后端在WebMethod中处理逻辑并返回结果
前端jQuery代码修正
原代码问题:
- 没有向后端传递必填的
names参数,缺少data字段 - 错误使用
fail回调,jQuery ajax的失败回调实际为error - ASP.NET WebMethod返回的JSON会默认包裹在
d字段中,直接将response对象拼接进DOM会显示[object Object],需要正确取值
修正后代码:
var jQueryXMLHttpRequest; $(document).ready(function () { readNamesSent(); }); // 读取StartingPage.aspx返回的名称列表 function readNamesSent() { jQueryXMLHttpRequest = $.ajax({ type: "POST", url: "StartingPage.aspx/sendString", contentType: "application/json; charset=utf-8", dataType: "json", // 不需要传参的话可以删掉这行,同时删掉后端方法的names参数 data: JSON.stringify({names: "你要传给后端的自定义内容"}), success: function (response) { // 解析返回值 var resData = JSON.parse(response.d); document.getElementById("status").innerHTML = resData.listOfName + "hi"; }, error: function (xhr, status, error) { // 排查错误时可以打印日志 console.log("请求出错:", error); } }); }
后端ASP.NET代码修正
原代码问题:
sendString方法存在拼写错误,return reutrnData是笔误- 方法上多余的
new关键字无意义,可以删除 - 读取文件的逻辑写在
openFile中无法被前端请求触发,需要移到sendString方法内 - 原代码没有实际读取目录下的文件名,返回的永远是空字符串
修正后代码:
using Newtonsoft.Json; using System.Collections.Generic; using System.IO; using System.Web.Services; public partial class StartingPage : System.Web.UI.Page { [WebMethod] // 不需要接收前端参数的话可以删掉方法的string names入参 public static string sendString(string names) { List<string> list = new List<string>(); string filepath2 = HttpContext.Current.Server.MapPath("~/MyFiles"); // 目录存在的话读取所有文件名 if (Directory.Exists(filepath2)) { string[] files = Directory.GetFiles(filepath2); foreach (var file in files) { list.Add(Path.GetFileName(file)); } } string name2 = string.Join("|", list.ToArray()); string returnData = JsonConvert.SerializeObject(new { listOfName = name2 }); return returnData; } }
额外注意事项
- 确保项目已经引用了Newtonsoft.Json包,否则
JsonConvert会报错 - 如果你需要后端主动推送数据到前端,AJAX无法实现该需求,需要换成SignalR这类实时通信方案
内容的提问来源于stack exchange,提问作者richie
相关产品推荐
相关产品推荐

