【发布时间】:2022-10-21 19:00:35
【问题描述】:
我花了 4 天时间尝试对我的.aspx.cs 进行 ajax 调用。在最好的情况下,我得到了 html 格式的答案。我不明白为什么会这样,也许我必须从 NuGet 添加一些库或在web.config 中写一些东西?
我尝试了什么:
- [HttpPost] [HttpGet]
- [网络方法]
- jQuery ajax 调用
- 更改网址
- 我的第一个应用程序是来自 VS 的带有 razor 页面的示例,我认为问题出在使用 razor 上,所以我创建了一个新项目 - 一个空的 Web 应用程序,但我仍然从服务器以 html 格式得到相同的答案。
我想得到什么:
我的应用程序模仿自动售货机。用户点击带有硬币的按钮,硬币必须在服务器端增加。 (BtnAddCoin()) 用户的硬币也总是显示在面板上。 (ShowInsertedCoins())
客户端.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) {
alert(coin);
var val1 = coin;
$.ajax({
type: "POST",
url: "/ClientSide.aspx/BtnAddCoin",
data: '{coin: "' + coin + '" }',
dataType: "text",
success: function (data) {
alert("AddCoin" + data);
},
error: function (req, status, error) {
alert(error + status);
}
}).done(function (result) { ShowInsertedCoin(); });
}
function ShowInsertedCoin() {
var insertedCoins = document.getElementById('InsertedCoins');
alert('ShowInsertedCoin');
$.ajax({
type: "GET",
url: "/ClientSide.aspx/ShowInsertedCoins",
dataType: "text",
data: {},
success: function (data) {
alert("ShowInsertedCoin " + data);
insertedCoins.textContent = data;
}
});
}
</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> 2 </a>
<a> 5 </a>
<a> 10 </a>
</div>
</div>
<div>
<p id="InsertedCoins" ><%=ShowInsertedCoins()%> </p>
</div>
</div>
</div>
</body>
</html>
客户端.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace VendingMachine
{
public partial class ClientSide : System.Web.UI.Page
{
static int coins = 10;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ShowInsertedCoins()
{
return "You inserted: " + coins.ToString();
}
[WebMethod]
public void BtnAddCoin(int coin)
{
coins = +coin;
//ShowInsertedCoins();
}
}
}
那么,如何使用 jQuery 或 js 对 .aspx.cs 进行 ajax 调用?
当我的函数必须返回一个字符串时,为什么我会得到 html 格式?
感谢您的关注和帮助。
【问题讨论】:
-
您可能需要考虑使用更新的技术。 Webforms 和 jQuery 在这一点上已经很老了。
-
@gunr2171 永远不会有足够的 jQuery ...
-
老实说,我明白了,有很多方法可以进行 ajax 调用,但是现在不明白什么是更好的新技术?
-
假设 jQuery 会做表单发布,也许将
'{coin: "' + coin + '" }'更改为{coin: coin }可能会起作用。如果 webmethod 将传入的表单变量映射到参数,那就是。 -
这回答了你的问题了吗? ASP.NET jQuery Ajax Calling Code-Behind Method