iT邦幫忙

3

[筆記系列] jQuery:簡易的Ajax與JSON參數傳值

  • 分享至 

  • xImage
  •  
//傳至後端之資料用Json包起來        
var sJson = JSON.stringify
({ 
sCustId: cid, 
sActivityId: activitVal
});


$.ajax({
    type: "POST",
    //async為false -> 同步 
    //async為true  -> 非同步
    async: false,   
    dataType: "json",
    url: "從根目錄開始或者相對路徑等等/指到的.aspx/function_01",
    //↑↑↑↑↑↑反正就是要指到你寫的aspx拉↑↑↑↑↑↑↑↑
    contentType: 'application/json; charset=UTF-8',
    data: sJson,
    success: function (msg) {
        //後端回傳的東西包成Object回來,
        //ex:{sResult = 例如在後端自己命名的某型別sResult物件}
        var sResult = msg.d.sResult;
        //後端回傳的東西包成Object回來,
        //ex:{db_Result = 例如在後端自己命名的DataTable物件}
        var db_Result = msg.d.db_Result;
        
        //do something
        },
        //statusCode範例
        statusCode: {
            403: function (response) {
                LocationHerf();
            }
        }
    }
});

var LocationHerf = function () {
    window.location.href = "你要轉page的URL拉";
};

//----------------------------------------------------


//後端程式碼範例 -- 中間內容不重要 主要看return包了什麼東西
[WebMethod(EnableSession = true)]
public static object function_01(string sCustId, string sActivityId)
{
    //判斷Session
    if (HttpContext.Current.Session["UserSession"] == null)
    {
        HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.Forbidden;
    }

    string sResult = string.Empty;
    string db_Result = string.Empty;
    string sql = string.Empty;
    Dictionary<string, object> dic = new Dictionary<string, object>();

    try
    {
        sql = @"SELECT * FROM ActivityRecord 
                WHERE CustomerId = @CustomerId
                AND ActivityId = @ActivityId";

        dic.Clear();
        dic.Add("@CustomerId", sCustId);
        dic.Add("@ActivityId", sActivityId);
        DataHelper dh = new DataHelper();
        DataTable dt = dh.queryData(sql, dic);
        int dbCount = dt.Rows.Count;
        //若資料庫找不到紀錄 表示 沒有重複
        if (dbCount == 0)
        {
            sResult = "success";
            //不重要 反正就是去call我另一個function去做事就是了 回傳DataTable
            db_Result = AddDbActivityRecord(sCustId, sActivityId);
        }
        else
        {
            sResult = "replay";
        }
    }
    catch (Exception ex)
    {
        sResult = ex.ToString();
    }
    finally
    {
        // 關閉連接
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["conStr"].ConnectionString.ToString());
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        dbTool.CloseDB(cmd, da);
    }
    return new
    {
        db_Result = db_Result,
        sResult = sResult
    };
}

若有錯誤請各路大神指教
純屬筆記筆記


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言