轉  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!")});


免責聲明!

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



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