WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据

WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据

WebForm1.aspx 页面 (原生AJAX请求,写法一)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="IsPostBack.WebForm1" %>  
  
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
"http://www.w3.org/1999/xhtml">  
"server">  
      
      
      
  
  
    
"form1" runat="server">
"t1"border="1px">
姓名年龄
"name">"age">
"button" onclick="btnClick()" value="提交"/>

WebForm1.aspx 页面 (AJAX请求,写法二,一般情况下我们用这种)

"server">  
      
      
      
  
  
    
"form1" runat="server">
"t1"border="1px">
姓名年龄
"name">"age">
"button" onclick="btnClick()" value="提交"/>

WebForm1.aspx.cs

如果你是try...catch里面使用了Response.End()的话,会被捕捉到一个异常:线程被中止"  解决方法:请点击
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data.SqlClient;  
using System.Data;  
  
namespace IsPostBack  
{  
    public partial class WebForm1 : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            string id = Request["id"]; //如果不是通过ajax 请求提交数据 就不会取到这个id ,所以此时的id 为null。但是如果是通过ajax请求提交数据,因为提交数据中有提交id,所以就能够取到这个id ,此时的id就有值了。  
  
            if (!string.IsNullOrEmpty(id)) // 如果不是通过ajax 请求提交数据 就不会进入花括号来调用GetUserData(string id) 方法  
            {  
  
                GetUserData(id); //如果是通过ajax请求提交数据,就会进入花括号来调用GetUserData(string id) 方法  
            }  
              
        }  
  
        void GetUserData(string id)  
        {  
            DataTable dt= SqlHelper.ExecuteDataTable("select * from T_User where id=@id", new SqlParameter("id", id));  
            string data= DataTableConvertJson.DataTableToJson("Json", dt);  
  
            Response.Write(data);  
            Response.End(); //将当前所有缓冲的输出发送到客户端,停止该页的执行,如果没有这一步的话,程序还会往后执行,除了把data输出到客户端之外,还会将webForm1.aspx里面的html代码都输出到页面。  
  
                        
  
        }  
    }  
}  

 

你可能感兴趣的:(WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据)