-1

我对从 javascript 调用 .cs 类文件(C#)函数有疑问 我的代码:我有像 call_cs_function_from_js 这样的类文件(.cs)

------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace call_cs_function_from_js
{
    public class cal_lcs_function_from_js
    {
        public void getdata()
        {

        }
    }
}

这是javascript代码文件:

<script type="text/javascript">
function call(){
  cal_lcs_function_from_js.getdata();  //This way is not working 
  alert('called');
}
</script>

在这里,我想从 call()(意思是 .js)调用 cal_lcs_function_from_js 的 getdata。call() 在按钮单击时调用。

请告诉我其他方法是什么。

4

2 回答 2

5

您不能直接从您的 javascript 代码调用您的 C# 函数。由于 javascript 在客户端运行,而您的 C# 函数驻留在服务器上。为此,您必须创建一个 Web 服务,并使用Ajax.

更新:

  1. 首先将命名空间添加using System.Web.Services;到您的网页。
  2. 将以下方法添加到您的页面

    [WebMethod]
    public string GetData()
    {
        return ("");
    }
    
  3. 使用 调用该方法Ajax

    $.ajax({ type: "GET", url: "/GetData", success: function (data) { });

于 2012-05-21T06:33:01.187 回答
0

使用 javascript 调用 C# 函数的唯一方法是在 ASP.NET 页面中运行 C# 函数。然后,您将使用来自 javascript 的 ajax 调用来调用 ASP.Net 页面并检索函数的结果。

http://api.jquery.com/jQuery.ajax/

function call(){
  $.ajax({
    url: "/cal_lcs_function_from_js"
  }).done(function() { 
    alert('called');
  });
}

其中“/cal_lcs_function_from_js”是在 ASP.net 中运行的页面,位于与运行 javascript 文件相同的 Web 服务器上。

于 2012-05-21T06:32:33.370 回答