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;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM