使用 ajax 分配文本框值 - 页面仍在刷新,分配的值已消失

Assign textbox values with ajax - page still refreshing and assigned values are gone

本文关键字:分配 刷新 消失 文本 ajax 使用      更新时间:2023-09-26

我正在尝试使用 AJAX 而不是 C# 填充网页的一部分,因为不应为此操作刷新网页。我需要做的就是运行 SELECT 查询并从 SQL DB 获取当前客户端并填写相关表单而不刷新页面。我设法获得了相关的客户端并更改了相关的文本框,但是,页面仍在刷新,所有文本框再次变为空!

我的代码如下:

    <asp:Panel ID="pnlClientSummaryDetails" runat="server" Width="360px" Visible="True">
       <asp:TextBox runat="server" ID="txtDateOpened"></asp:TextBox>
       <!--other text boxes -->
    </asp:Panel>
    <asp:Button ID="bnSelectClient" runat="server" CssClass="auto-style7" Text="Select Client" ToolTip="Click the view client button to view selected clients information" Width="282px" OnClientClick="BindClientSummaryForm()" />
    function BindClientSummaryForm() {
            $.ajax({
                type: "POST",
                url: "Clients.aspx/GetClientSummaryData",
                contentType: "application/json;charset=utf-8",
                data: {},
                dataType: "json",
                success: function(data) {
                    document.getElementById('<%= txtDateOpened.ClientID %>').value = data.d.DateFileOpened;
                  // other textboxes will be filled like that.
                },
                error: function (result) {
                    alert("Error occured while filling ClientSummary part.");
                }
            });
        }
[WebMethod] 
        public static MyClient GetClientSummaryData() //GetData function
        {
            //FillClientSummaryGridView();
            int intClientID = 0; 
            Int32.TryParse(clientID, out intClientID);
            MyClient client = new MyClient();
            string sQuery = "SELECT ClientID,FirstName,DateFileOpened FROM dbo.Client where ClientID = " + intClientID;
            String sConnectionString = ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString;
            SqlConnection con = new SqlConnection(sConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(sQuery, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtGetData = new DataTable();
            da.Fill(dtGetData);
            foreach(DataRow dtRow in dtGetData.Rows)
            {
                client.Firstname = dtRow.ItemArray[1].ToString();
                client.DateFileOpened = dtRow.ItemArray[2].ToString();            
            }
            return client;
        }

朋友,我该怎么办?我必须阻止页面刷新并保留由 ajax 的成功部分分配的文本框值。谢谢!

请尝试在

ajax 调用后将返回 false 添加到您的 BindClientSummaryForm 函数中,同时将调用该函数的方式修改为: OnClientClick="return BindClientSummaryForm();"

如果这不起作用,请尝试从函数中删除返回 false 并改用它:OnClientClick="BindClientSummaryForm(); 返回 false;"