Ajax无刷新显示

前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="QianBao.Dictionary.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 id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ajax实例1</title>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn1").click(function () {
                var txtparam1 = $("#txtParam1").val();
                var txtparam2 = $("#txtParam2").val();

                $.ajax({
                    url: "WebForm1.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>

后台

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 QianBao.Dictionary
{
    public partial class WebForm1 : 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;
        }
    }
}
原文地址:https://www.cnblogs.com/yuanyanyan/p/6541623.html