使用jQuery的getJSON方法和ASP.NET Web窗体

时间:2009-07-24 09:29:26

标签: asp.net jquery webforms getjson

如何使用jQuery上的getJSON方法在ASP.NET Web窗体页面上调用方法?

目标是:

  1. 用户点击列表项
  2. 该值将发送到服务器
  3. 服务器使用相关的内容列表进行响应,使用JSON
  4. 格式化
  5. 填充辅助框
  6. 我不想使用UpdatePanel,我已经使用ASP.NET MVC框架完成了数百次,但无法使用Web窗体来解决这个问题!

    到目前为止,我可以做任何事情,包括调用服务器,它只是没有调用正确的方法。

    谢谢,
    基隆

    一些代码:

    jQuery(document).ready(function() {
       jQuery("#<%= AreaListBox.ClientID %>").click(function() {
           updateRegions(jQuery(this).val());
       });
    });
    
    function updateRegions(areaId) {
        jQuery.getJSON('/Locations.aspx/GetRegions', 
            { areaId: areaId },
            function (data, textStatus) {
                debugger;
            });
    }
    

3 个答案:

答案 0 :(得分:26)

这是一个简约的例子,希望能帮助你入门:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>

<script runat="server">
    [WebMethod]
    public static string GetRegions(int areaId)
    {
        return "Foo " + areaId;
    }
</script>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jQuery and page methods</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
    $(function() {
        var areaId = 42;
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetRegions",
            data: "{areaId:" + areaId + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
               alert(data.d);
           }
        });
    });
    </script>
</body>
</html>

答案 1 :(得分:0)

我稍稍调整了你的代码。我将ClientID的服务器端输出添加到updateRegions方法以将其传入。并且我更改了您的getJSON方法以使用查询字符串参数(而不是单独的数据)和回调函数传递url。

jQuery(document).ready(function() {
   jQuery("#<%= AreaListBox.ClientID %>").click(function() {
       updateRegions(<%= AreaListBox.ClientID %>);
   });
});

function updateRegions(areaId) {
    jQuery("h2").html("AreaId:" + areaId);

    jQuery.getJSON("/Locations.aspx/GetRegions?" + areaId, 
        function (data, textStatus) {
            debugger;
        });
}

让我知道这是否有效!

答案 2 :(得分:0)

您也可以使用GetJSON,但在这种情况下您应该更改WebMethod。你应该用:

来装饰它
[WebMethod(EnableSession = true)]       
[ScriptMethod(UseHttpGet =false, ResponseFormat = ResponseFormat.Json)]

做一个获取可能不是你想要的。