jquery - 使用 jQuery ajax 从客户端调用时服务器代码未触发
问题描述
我正在尝试使用 jQuery ajax 从客户端调用服务器端方法。服务器方法从不触发或抛出错误。它根本什么都不做。我正在使用 .NET 4.6.1 版。该项目是使用 Visual Studio 2017 创建的,使用的项目模板是“ASP.NET Web Forms Site”。我通过搜索 Stack Overflow 获得了大部分客户端代码。我的问题得到了多次点击,但似乎没有一个有效。我还尝试了一个简单的 jQuery 调用,方法是给 div 一个 id 并隐藏它,即$("#test").hide();
. 该测试调用运行良好,因此我有理由确定 jQuery 本身正在运行。我还尝试了方法中的服务器方法代码Page_Load
,它工作正常。
这是我的客户代码:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/SayHello",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
alert('success');
}
</script>
<div class="row">
<h1>AJAX Test</h1>
</div>
</asp:Content>
这是我的服务器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void SayHello()
{
System.IO.File.WriteAllText(@"C:\Temp\WriteText.txt", "hello");
}
}
解决方案
推荐阅读
- python - 在 Python 中未选择选项时循环的简单循环
- android - 模拟器:PANIC:损坏的 AVD 系统路径。检查您的 ANDROID_SDK_ROOT 值 [C:\Users\Public\Android\Sdk]
- jsp - 只显示表达式语言值一次
- python - 我的爬取代码不打印任何结果
- linux - 制作一个 bash 函数,在参数中使用一些特殊字符
- list - Prolog 从列表中删除元素
- javascript - this.state.item.id 未定义。反应式
- python - 我可以为 gevent 池设置最大任务或最大内存限制吗?
- ios - SignIn with Apple 的自定义圆形按钮
- java - 在活动之间同时发送数据,同时不断更新数据