【问题标题】:Jquery AJAX with ASP.NET WebMethod refreshing the entire pageJquery AJAX 与 ASP.NET WebMethod 刷新整个页面
【发布时间】:2011-10-23 12:39:53
【问题描述】:

我正在使用 Jquery Ajax 在我的表单中设置标签和列表框的值。我意识到值是由函数正确设置的。但就在那之后,页面只是刷新清除所有先前设置的值。为什么会这样?我是 Jquery/Ajax 的新手。我在这里缺少任何基础知识吗?提前致谢。

我正在粘贴整个代码

        $(document).ready(function () {
            $('#Button1').bind('click', function clk() {
                $.ajax({
                    type: "POST",
                    url: "WebForm5.aspx/TestMethod",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        alert(result.d.ListBox.length);
                        for (var i = 0; i < result.d.ListBox.length; i++) {
                            alert(result.d.ListBox[i]);
                            $(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
   .appendTo('#<%=ListBox1.ClientID  %>');

                            $('#Label1').text(result.d.MyProperty);
                        }
                    }
                });
            })
        });                   

【问题讨论】:

    标签: c# javascript jquery .net ajax


    【解决方案1】:

    Button1 在您的代码中是一个 asp 按钮,它是一个提交按钮。当你点击它时,它会提交页面并刷新整个页面。如果你想阻止页面提交按钮点击return false,它会起作用。

    $('#Button1').bind('click', function clk() {
                    $.ajax({
                        type: "POST",
                        url: "WebForm5.aspx/TestMethod",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
                            alert(result.d.ListBox.length);
                            for (var i = 0; i < result.d.ListBox.length; i++) {
                                alert(result.d.ListBox[i]);
                                $(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
       .appendTo('#<%=ListBox1.ClientID  %>');
    
                                $('#Label1').text(result.d.MyProperty);
                            }
                        }
                    });
    
      return false;
                })
    

    【讨论】:

    • ..谢谢..完美运行..你能告诉我为什么会发生这种情况以及“return false”是如何做到的吗?
    • 在我的回答中添加了解释看看。
    • 非常感谢!我一直在寻找为什么我的按钮会自动刷新。我添加了 return false 并且它完全按预期工作。
    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 2019-03-30
    • 2010-10-05
    • 2010-10-09
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多