JS AJAX前臺(tái)如何給后臺(tái)類的函數(shù)傳遞參數(shù)

字號(hào):


    這篇文章主要介紹了JS AJAX前臺(tái)給后臺(tái)類的函數(shù)傳遞參數(shù)的方法,下面有個(gè)不錯(cuò)的示例,需要的朋友可以參考下
    將普通頁(yè)面的方法公布為WebMethod,以Javascript形式訪問(wèn)。
    1 方法要public static修飾,返回類型最好是string。
    2 方法前添加[WebMethod] 特性。
    3 Client端訪問(wèn)時(shí)要使用Post方法,和Json作為數(shù)據(jù)形式進(jìn)行交互。否則會(huì)整頁(yè)HTML返回。
    4 在jQuery訪問(wèn)時(shí),回調(diào)中的data.d才時(shí)真正的返回內(nèi)容。
    5 訪問(wèn)URL為: http://abc.com/abc.aspx/GetTime 如有個(gè)GetTime的公共靜態(tài)方法。
    [WebMethod]
    2
    public
    static
    string
    GetTime()
    3
    {
    4
    return
    DateTime.Now.ToString(
    "yyyy-MM-dd HH:mm:ss"
    );
    5
    }
    ---------------
    腳本(以jQuery為例調(diào)用)
    $.ajax({
    2
    url:url,
    3
    method:
    "post"
    ,
    4
    dataType:
    "json"
    ,
    5
    contentType:
    "application/json; charset=UTF-8"
    ,
    6
    success:
    function
    (data){
    7
    $(
    "#id"
    ).html(data.d);
    //見第3點(diǎn)
    8
    }
    9
    });