首页 > 解决方案 > 使用 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");
    }
}

标签: jqueryasp.netajaxhttppost

解决方案


推荐阅读