• C#中jQuery Ajax实例(一)


    目标:在aspx页面输入两参数,传到后台.cs代码,在无刷新显示到前台

    下面是我的Ajax异步传值的第一个实例

    1.前台html代码:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Ajax实例1</title>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btn1").click(function () {
                    var txtparam1 = $("#txtParam1").val();
                    var txtparam2 = $("#txtParam2").val();
    
                    $.ajax({
                        url: "demo1.aspx/AjaxMethod",//发送到本页面后台AjaxMethod方法
                        type: "POST",
                        dataType: "json",
                        async: true,//async翻译为异步的,false表示同步,会等待执行完成,true为异步
                        contentType: "application/json; charset=utf-8",//不可少
                        data: "{param1:'" + txtparam1 + "',param2:'" + txtparam2 + "'}",
                        success: function (data) {
                            $("#result").html(data.d);
                        },
                        error: function () {
                            alert("请求出错处理");
                        }
                    });
    
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            参数1:<input type="text" id="txtParam1" value="" /><br />
            参数2:<input type="text" id="txtParam2" value="" /><br />
            <input type="button" id="btn1" value="提交"/><br />
            <div id="result"></div>
        </form>
    </body>
    </html>

    2.后台代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace AjaxDemo
    {
        public partial class demo1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
            }
    
            //type方式必须是post,方法必须是静态的,方法声明要加上特性[System.Web.Services.WebMethod()],传递的参数个数也应该和方法的参数相同。
            [System.Web.Services.WebMethod()]
            public static string AjaxMethod(string param1, string param2)
            {
                return "参数1为:"+param1+",参数2为:"+param2;
            }
        }
    }

    3.运行效果:

    4.输入数据,点击提交后:

     5.注意:

    第1步中contentType: "application/json; charset=utf-8"这句不可少!不设置这个,json也是返不回来的

    当然,你也可以如下这种Post传值格式写:

    var data={"name":"Tom","age":"20"};
    var url="XXX.ashx"
    $.post(url,data,function (){alert("ok!")});
  • 相关阅读:
    Oracle 11g系列:函数与存储过程
    Oracle 11g系列:视图
    Oracle 11g系列:约束
    Oracle 11g系列:数据表对象
    Oracle 11g系列:数据库
    Oracle 11g系列:SQL Plus与PL/SQL
    Ext.util.TaskRunner定时执行任务
    MS SQL Server存储过程
    UML基础:用例图Use Case Diagram(1)
    UML基础系列:类图
  • 原文地址:https://www.cnblogs.com/qk2014/p/4438693.html
Copyright © 2020-2023  润新知