如何通过AJAX调用aspx.vb后端方法并传递数组参数,报401错误如何解决
问题排查与修复方案
1 解决401状态码报错
401代表请求未授权,先调整Web.config配置放开WebMethod访问权限:
在<system.web>节点下添加如下配置:
<webServices> <protocols> <add name="HttpPost"/> </protocols> </webServices>
如果站点启用了Forms认证,还需要给当前页面单独开放权限,在<configuration>根节点下添加:
<location path="NewScenarioProfilePage.aspx"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location>
注意:后端不要使用MsgBox方法,Web服务运行在服务端,桌面弹窗无法显示还会阻断代码执行,调试时直接打断点即可。
2 修正前端传值逻辑
你当前获取的Years是DOM元素集合,不是数值数组,需要先提取选中项的数值,再通过标准JSON序列化传递,不要手动拼接JSON字符串避免格式错误:
修改后的JS代码如下:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $("#Button1").click(function () { // 提取选中项的数值转为整数数组 var yearElements = document.getElementById("Options").querySelectorAll(".selected"); var Years = Array.from(yearElements).map(el => parseInt(el.value || el.textContent.trim())); $.ajax({ type: "POST", url: "NewScenarioProfilePage.aspx/CalculateSum", data: JSON.stringify({ yearvalue: Years }), contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: function (response) { // jQuery失败回调是error不是failure alert(response.responseJSON?.d || "接口调用失败"); } }); }); </script>
3 修正后端参数类型
你需要接收可能多值的参数,直接把参数类型定义为整数数组即可,无需兼容单值类型,前端传单个值时也包在数组里传递,后端统一处理逻辑更简单:
修改后的VB后端代码如下:
<System.Web.Services.WebMethod()> Public Shared Function CalculateSum(ByVal yearvalue As Integer()) As String Dim Result As Integer = 0 ' 遍历数组求和,仅单值时也能正常计算 For Each y As Integer In yearvalue Result += y Next Return Result.ToString() End Function
内容的提问来源于stack exchange,提问作者Reem Elshenawy
相关产品推荐
相关产品推荐

