1. 程式人生 > 實用技巧 >asp.net 利用Ajax和Jquery在前臺向後臺傳引數並返回值

asp.net 利用Ajax和Jquery在前臺向後臺傳引數並返回值

方案一 直接呼叫後臺

 1 <script src="js/jquery-1.9.1.js" type="text/javascript"></script>
 2     
 3 <script type="text/javascript">
 4 
 5         $(function () {
 6 
 7             $('#txtUserName').blur(function () {
 8 
 9                 var username = $(this).val();
10 
11                 $.ajax({
12 13 type: "post", 14 15 contentType: "application/json",//傳值的方式 16 17 url: "WebAjaxForMe.aspx/GetValueAjax",//WebAjaxForMe.aspx為目標檔案,GetValueAjax為目標檔案中的方法 18 19 data: "{username:'" + username + "'}",//username 為想問後臺傳的引數(這裡的引數可有可無)
20 21 success: function (result) { 22 23 alert(result.d);//result.d為後臺返回的引數 24 25 } 26 27 }) 28 29 }) 30 31 }) 32 33 </script> 34 35 //這裡是引數的來源 36 37 <input id="txtUserName" type="
text" />
1 [WebMethod]//方法前邊必須新增 [WebMethod]       
2 
3 public static string GetValueAjax(string username)//這個方法需要是靜態的方法要用到關鍵字static        
5 {
6    //在這裡可以對傳進來的引數進行任何操作            
7   return username;     
8 }

方案二 一般處理程式

 1  <%--引入JQuery--%>
 2      <script src="js/jquery-2.1.1.min.js"></script>
 3 
 4      <%--使用AJAX向一般處理程式傳遞引數,呼叫函式--%>
 5      <script type="text/javascript">
 6          $(function () {
 7               <%--當txtYiBan失去焦點的時候觸發--%>
 8              $('#txtYiBan').blur(function () {
 9                  var username = $(this).val();
10                  $.ajax({
11                      type: "GET",
12                      url: "ajaxtest.ashx?json=" + username,//ajaxtest.ashx為目標檔案
13                      dataType: "text",
14                      success: function (result) {
15                          alert(result.d);//result.d為後臺返回的引數
16                      }
17                  })
18              })
19          })
20     </script>
21 
22 <input id="txtYiBan" type="text" />

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 using System.Web.SessionState;
 7 
 8 namespace aspAjaxTest
 9 {
10     /// <summary>
11     /// ajaxtest 的摘要說明
12     /// </summary>
13     [WebService(Namespace = "http://tempuri.org/")]
14     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
15     public class ajaxtest : IHttpHandler
16     {
17         HttpContext Context;
18         /// <summary>
19         /// 獲取傳的值,並呼叫其他的方法
20         /// </summary>
21         /// <param name="context"></param>
22         public void ProcessRequest(HttpContext context)
23         {
24             Context = context;
25             context.Response.Clear();
26             context.Response.ContentType = "text/html; charset=utf-8";
27             //獲取傳來的值
28             string methodName = GetQueryString("json");
29 
30             //可以呼叫其他方法------看下文
31         }
32         /// <summary>
33         /// 獲取傳的值
34         /// </summary>
35         /// <param name="name"></param>
36         /// <returns></returns>
37         string GetQueryString(string name)
38         {
39             //獲取傳的值
40             return Context.Request.Params[name];
41         }
42 
43         public bool IsReusable
44         {
45             get
46             {
47                 return false;
48             }
49         }
50     }
51 }

  • 在aspx的後臺可以用如下的方式來捕獲引數:

  workstateValue =Request.QueryString["workstateValue"];

  • 在一般處理程式中可以用:

  return Context.Request.Params[name];

JQuery在asp.net中三種ajax傳值

1)通過webservice,注意去掉註釋[System.Web.Script.Services.ScriptService]這行前的註釋

2)通過aspx.cs檔案中的靜態方法

3)通過aspx檔案url

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="asp.net.WebForm1" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
 8     <script type="text/javascript">
 9         function Ws() {
10             $.ajax({
11                 type: "POST",
12                 contentType: "application/json; charset=utf-8",
13                 url: "WebService1.asmx/HelloWorld2",
14                 data: "{name:'xiaoxiao'}",
15                 dataType: 'json',
16                 success: function (result) {
17                     alert(result.d);
18                 }
19             });
20         }
21         function StaticMethod() {
22             $.ajax({
23                 type: "POST",
24                 contentType: "application/json; charset=utf-8",
25                 url: "aspxpage.aspx/SayHello2",
26                 data: "{name:'xiaoxiao'}",
27                 dataType: 'json',
28                 success: function (result) {
29                     alert(result.d);
30                 }
31             });
32 
33         }
34         function FromPage() {
35             $.ajax({
36                 type: "POST",
37                 contentType: "application/json; charset=utf-8",
38                 url: "dataContent.aspx?nowtime='" + new Date() + "'",
39                 data: "{}",
40                 dataType: 'html',
41                 success: function (result) {
42                     alert(result);
43                 }
44             });
45 
46         }
47 
48     </script>
49 </head>
50 <body>
51     <form id="form1" runat="server">
52      
53     <div>
54         <input id="Button1" type="button" value="jquery呼叫WebService" onclick="Ws()" />
55     </div>
56     <div>
57         <input id="Button2" type="button" value="jquery呼叫aspx頁面靜態方法" onclick="StaticMethod()" />
58     </div>
59     <div>
60         <input id="Button3" type="button" value="jquery通過page儲存值" onclick="FromPage()" />
61     </div>
62     </form>
63 </body>
64 </html>
前臺code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 
 7 namespace asp.net
 8 {
 9     /// <summary>
10     /// WebService1 的摘要說明
11     /// </summary>
12     [WebService(Namespace = "http://tempuri.org/")]
13     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
14     [System.ComponentModel.ToolboxItem(false)]
15     // 若要允許使用 ASP.NET AJAX 從指令碼中呼叫此 Web 服務,請取消對下行的註釋。
16      [System.Web.Script.Services.ScriptService]
17     public class WebService1 : System.Web.Services.WebService
18     {
19 
20         [WebMethod]
21         public string HelloWorld()
22         {
23             return "Hello World"+System.DateTime.Now.ToLongTimeString();
24         }
25 
26         [WebMethod]
27         public string HelloWorld2(string name)
28         {
29             return "Hello World" + name + System.DateTime.Now.ToLongTimeString();
30         }
31     }
32 }
webservice中code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Web.Services;
 8 
 9 namespace asp.net
10 {
11     public partial class aspx頁面代替ws : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15            
16         }
17         [WebMethod] 
18         public static string SayHello()
19         {
20             return "Hello";
21         }
22 
23         [WebMethod]
24         public static string SayHello2(string name)
25         {
26             return "Hello"+name;
27         }
28     }
29 }
aspx.cs中code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.IO;
 8 
 9 namespace asp.net
10 {
11     public partial class dataContent : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15             Response.Clear();
16             Page.ViewStateMode = ViewStateMode.Disabled;
17             if (Request.QueryString["nowtime"] != null)
18             {
19                 string stime = Request.QueryString["nowtime"].ToString();
20                 Response.Write(stime);
21             }
22             Response.Flush();
23           
24         }
25     }
26 }
用url傳值 通過aspx頁面儲存資料