【问题标题】:Call Javascript method from .ashx file从 .ashx 文件调用 Javascript 方法
【发布时间】:2012-10-07 14:58:12
【问题描述】:

根据我之前的问题(Create json using JavaScriptSerializer),在.ashx 文件中,我正在使用以下方法打印 json 对象:

context.Response.ContentType = "application/json";
context.Response.Write(json);

我从 default.aspx 调用这个 .ashx 文件,该文件在其 <head> 标记内有一些 javascript 函数。 我的问题是
context.Response.Write(json); 之后,我将如何从 .ashx 文件中调用 javascript 函数?

更新
我的最终目标是为 DataTable 实现Server Side Processing。我想使用 javascript 函数将行与上下文菜单绑定。 为此,我使用以下代码调用.ashx 文件:

 $('#example').dataTable({
            'bProcessing': true,
            'bServerSide': true,
            'sAjaxSource': '/data.ashx'
        });

【问题讨论】:

    标签: javascript asp.net generic-handler


    【解决方案1】:

    你在使用 ajax 请求吗?在这种情况下,您可以使用 javascript 中可用的成功方法,如 w3schools 中的以下示例所示:

    function showHint(str)
    {
    var xmlhttp;
    if (str.length==0)
      { 
      document.getElementById("txtHint").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        // You can call your custom method here...  
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","gethint.asp?q="+str,true);
    xmlhttp.send();
    

    }

    或者如果您使用的是 jquery:

    $.ajax({
      url: "test.html",
      context: document.body
    }).done(function() { 
      // You can call your custom method here... 
      $(this).addClass("done");
    });
    

    更新

    查看:http://datatables.net/usage/callbacks可以使用的方法是:fnInitComplete

    例如

    $('#example').dataTable({
                'bProcessing': true,
                'bServerSide': true,
                'sAjaxSource': '/data.ashx',
                'fnInitComplete' : function() {
                    alert('Your menu population code here!');
                 }
            });
    

    【讨论】:

    • 对不起,我早该提到我如何调用.ashx 文件。请查看问题的更新部分。
    【解决方案2】:

    你可以使用

    eval
    

    在客户端将响应评估为 javascript。但我怀疑你真的需要或想要这个,它可能不是一个非常优雅的解决方案。那么你想归档什么?

    【讨论】:

    • 我不知道eval 是如何工作的...请您为我澄清一下吗?我的最终目标是实现Server Side Processing for DataTable。我想使用javascript函数将行与上下文菜单绑定。
    • eval 接受一个字符串参数,其中包含要执行的 javascript 代码。为什么不将 HTML 类属性分配给服务器端的行(例如主行、子行、带有特殊上下文菜单的行)并运行客户端 javascript 来分配相应的上下文- 得到响应后每个行类的菜单?
    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多