如何在 javascript 函数中调用服务器端函数

How to call a Server Side Function in a javascript Function

本文关键字:函数 服务器端 调用 javascript      更新时间:2023-09-26

我有一个按钮,点击时会执行这个:

protected void Button6_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), 
                    "myScript", "AnotherFunction();", true);
}

我还有另一个服务器端功能,它是这样的:

public void Delete()
{
  //Delete Code
}

单击按钮后,它现在将转到此javascript功能:

现在我想做的是,在服务器端调用Delete()函数。这是我到目前为止尝试过的javascript函数

function (isConfirm) 
{
   if (isConfirm)
   {
       //CALL DELETE FUNCTION HERE Delete();
       swal("Deleted!", "Your imaginary file has been deleted.", "success");
   }
   else
   {
       swal("Cancelled", "Your imaginary file is safe :)", "error");
   }
 });

如何调用该服务器端函数?知道吗?

您可以通过两种方式实现此目的。Ajax/Web Service 或 JS 中的触发按钮单击。最简单的是触发按钮单击。使用以下代码。

.aspx:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" ClientIDMode="Static" style="display:none;"/>

C#:

protected void Button1_Click(object sender, EventArgs e)
{
      Delete();
}

.JS:

document.getElementById('Button1').click();
// jquery
$("#Button1").click();

但是,如果您不想回发页面,请使用 Ajax。在Ajax简单中,你需要添加一个网页说data.aspx,在后端类的数据中.aspx你会添加以下c#

阿贾克斯。C#

 [WebMethod]
 public static int DoSomething(int Id)
 {
       return 1;
 }

现在你可以从JS调用它:

$.ajax({
            url: APP_PAGE_RELATIVE_PATH + "Data.aspx/DoSomething",
            data: "{'Id':5}",
            type: "POST",
            cache: false,
            headers: { "cache-control": "no-cache" },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                // Do Something
            },
            error: function (xhr, status, error) {
                //DebugAlert("Error: " + xhr.responseText);
            }
        });

我会向页面添加一个脚本管理器并启用页面方法;

并编码:

在 ASPX 中:

<asp:ScriptManager runat="server" EnablePageMethods="true" />

在Javascript中:

<script>
     PageMethods.Delete();        
</script>

在ASPX.cs中:

[System.Web.Services.WebMethod]
public static void Delete()
{
     //Delete Code
}