简体   繁体   中英

Jquery AJAX with ASP.NET WebMethod refreshing the entire page

I am using Jquery Ajax to set the values of a Label and a ListBox in my form. I realize that values are set properly by the function. But just after that, the page just refreshes clearing all previously set values. Why is this happening? Iam new to Jquery/Ajax. Am I missing any fundamentals here? Thanks in Advance.

Iam pasting the entire code

        $(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);
                        }
                    }
                });
            })
        });                   

Button1 in your code is an asp button which is a submit button. When you click on it, it will submit the page and refresh the whole page. If you want to stop the page from being submitted on button click return false , it will work.

$('#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;
            })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM