You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery/JS调用.aspx.cs的Ajax接口?返回HTML问题排查

问题描述

用户耗时4天尝试对ASP.NET WebForms的.aspx.cs文件发起Ajax调用,始终返回HTML格式结果而非预期字符串。已尝试添加[HttpPost]/[HttpGet]特性、使用[WebMethod]、编写jQuery Ajax请求、修改请求URL等操作,从Razor页面项目切换为空Web应用后问题仍存在。需求为实现模拟自动售货机:点击硬币按钮后服务器端硬币数累加(对应BtnAddCoin()方法),并实时显示已投入硬币数(对应ShowInsertedCoins()方法)。

问题分析与修复步骤

  • GET请求未启用:默认[WebMethod]不允许GET访问,需给查询方法添加[ScriptMethod(UseHttpGet = true)]特性,并引入System.Web.Script.Services命名空间。
  • POST请求缺少正确Content-Type:jQuery Ajax POST请求必须指定contentType: "application/json; charset=utf-8",否则服务器无法解析JSON参数,会返回整个页面HTML。
  • 参数传递格式错误:手动拼接JSON字符串易出语法错误,应使用JSON.stringify()生成标准JSON数据。
  • 硬币累加逻辑错误:BtnAddCoin方法中coins = +coin;是赋值操作而非累加,需改为coins += coin;。
  • WebMethod返回值结构:ASP.NET WebForms的[WebMethod]返回结果会被自动包裹在d属性中,客户端需通过data.d获取实际内容。

修改后的ClientSide.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientSide.aspx.cs" Inherits="VendingMachine.ClientSide" Async="true" AsyncTimeout="60"  %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <link rel="stylesheet" href="StyleSheet.css" />
    <title></title>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    function AddCoin(coin) {
        $.ajax({
            type: "POST",
            url: "/ClientSide.aspx/BtnAddCoin",
            data: JSON.stringify({coin: coin}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                ShowInsertedCoin();
            },
            error: function (req, status, error) {
                alert(error + " " + status);
            }
        });
    }

    function ShowInsertedCoin() {
        var insertedCoins = document.getElementById('InsertedCoins');
        $.ajax({
            type: "GET",
            url: "/ClientSide.aspx/ShowInsertedCoins",  
            dataType: "json",
            success: function (data) {  
                insertedCoins.textContent = data.d;
            },
            error: function(req, status, error) {
                alert(error + " " + status);
            }
        });
    }
</script>
</head>
<body>
    <form id="form1" runat="server">     
    </form>
     <div>
        <h1>Coffee machine</h1>
     </div>
    <div> 
        <div>
                <p> Add coins: </p>           
            <div>                
                <div>          
                         <a id ="coin1" onclick="AddCoin(1)"> 1 </a>
                         <a onclick="AddCoin(2)"> 2 </a>
                         <a onclick="AddCoin(5)"> 5 </a>
                         <a onclick="AddCoin(10)"> 10 </a>
                     </div>
                </div>
            <div>
                <p id="InsertedCoins" ><%= ShowInsertedCoins() %> </p>
            </div>
            </div>  
    </div>
</body>
</html>

修改后的ClientSide.aspx.cs

using System;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;

namespace VendingMachine
{
    public partial class ClientSide : Page
    {     
        static int coins = 10;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public static string ShowInsertedCoins()
        {
            return "You inserted: " + coins.ToString();
        }

        [WebMethod]
        public static void BtnAddCoin(int coin)
        {
            coins += coin;
        }         
    }
}

额外说明

  • 无需额外安装NuGet包,默认WebForms项目已包含所需程序集。
  • web.config无需特殊修改,确保项目类型为ASP.NET WebForms即可。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:01:02