asp.net 利用Ajax和Jquery在前台向后台传参数并返回值

方案一 直接调用后台

<script src="js/jquery-1.9.1.js" type="text/javascript"></script>
    
<script type="text/javascript">

        $(function () {

            $(‘#txtUserName‘).blur(function () {

                var username = $(this).val();

                $.ajax({

                    type: "post",

                    contentType: "application/json",//传值的方式

                    url: "WebAjaxForMe.aspx/GetValueAjax",//WebAjaxForMe.aspx为目标文件,GetValueAjax为目标文件中的方法

                    data: "{username:‘" + username + "‘}",//username 为想问后台传的参数(这里的参数可有可无)

                    success: function (result) {

                        alert(result.d);//result.d为后台返回的参数

                    }

                })

            })

        })

    </script>

  //这里是参数的来源

   <input id="txtUserName" type="text" />
[WebMethod]//方法前边必须添加 [WebMethod]       

public static string GetValueAjax(string username)//这个方法需要是静态的方法要用到关键字static        
{
   //在这里可以对传进来的参数进行任何操作            
  return username;     
}

方案二 一般处理程序

<%--引入JQuery--%>
     <script src="js/jquery-2.1.1.min.js"></script>

     <%--使用AJAX向一般处理程序传递参数,调用函数--%>
     <script type="text/javascript">
         $(function () {
              <%--当txtYiBan失去焦点的时候触发--%>
             $(‘#txtYiBan‘).blur(function () {
                 var username = $(this).val();
                 $.ajax({
                     type: "GET",
                     url: "ajaxtest.ashx?json=" + username,//ajaxtest.ashx为目标文件
                     dataType: "text",
                     success: function (result) {
                         alert(result.d);//result.d为后台返回的参数
                     }
                 })
             })
         })
    </script>

<input id="txtYiBan" type="text" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;

namespace aspAjaxTest
{
    /// <summary>
    /// ajaxtest 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ajaxtest : IHttpHandler
    {
        HttpContext Context;
        /// <summary>
        /// 获取传的值,并调用其他的方法
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            Context = context;
            context.Response.Clear();
            context.Response.ContentType = "text/html; charset=utf-8";
            //获取传来的值
            string methodName = GetQueryString("json");

            //可以调用其他方法------看下文
        }
        /// <summary>
        /// 获取传的值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        string GetQueryString(string name)
        {
            //获取传的值
            return Context.Request.Params[name];
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
  • 在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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="asp.net.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function Ws() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService1.asmx/HelloWorld2",
                data: "{name:‘xiaoxiao‘}",
                dataType: ‘json‘,
                success: function (result) {
                    alert(result.d);
                }
            });
        }
        function StaticMethod() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "aspxpage.aspx/SayHello2",
                data: "{name:‘xiaoxiao‘}",
                dataType: ‘json‘,
                success: function (result) {
                    alert(result.d);
                }
            });

        }
        function FromPage() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "dataContent.aspx?nowtime=‘" + new Date() + "‘",
                data: "{}",
                dataType: ‘html‘,
                success: function (result) {
                    alert(result);
                }
            });

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
     
    <div>
        <input id="Button1" type="button" value="jquery调用WebService" onclick="Ws()" />
    </div>
    <div>
        <input id="Button2" type="button" value="jquery调用aspx页面静态方法" onclick="StaticMethod()" />
    </div>
    <div>
        <input id="Button3" type="button" value="jquery通过page存储值" onclick="FromPage()" />
    </div>
    </form>
</body>
</html>

前台code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace asp.net
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
     [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World"+System.DateTime.Now.ToLongTimeString();
        }

        [WebMethod]
        public string HelloWorld2(string name)
        {
            return "Hello World" + name + System.DateTime.Now.ToLongTimeString();
        }
    }
}

webservice中code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace asp.net
{
    public partial class aspx页面代替ws : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        [WebMethod] 
        public static string SayHello()
        {
            return "Hello";
        }

        [WebMethod]
        public static string SayHello2(string name)
        {
            return "Hello"+name;
        }
    }
}

aspx.cs中code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace asp.net
{
    public partial class dataContent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Page.ViewStateMode = ViewStateMode.Disabled;
            if (Request.QueryString["nowtime"] != null)
            {
                string stime = Request.QueryString["nowtime"].ToString();
                Response.Write(stime);
            }
            Response.Flush();
          
        }
    }
}

用url传值 通过aspx页面保存数据

相关推荐