0

我似乎在从 jQuery 调用 WebMethod 时遇到问题,我使用这篇文章作为我的起点:

http://www.misfitgeek.com/2011/05/calling-web-service-page-methods-with-jquery/

JS

    function WebMethod(fn, paramArray, successFn, errorFn) 
     {
        //----------------------------------------------------------------------+
        // Create list of parameters in the form:                               |
        // {'paramName1':'paramValue1','paramName2':'paramValue2'}              |
        //----------------------------------------------------------------------+
        var paramList = '';
        if (paramArray.length > 0) {
            for (var i = 0; i < paramArray.length; i += 2) {
                if (paramList.length > 0) paramList += ',';
                paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
            }
        }

        paramList = '{' + paramList + '}';

        //----------------------------------------------------------------------+
        // Call the WEB method                                                  |
        //----------------------------------------------------------------------+
        $.ajax({
            type: 'POST',
            url: 'ContractView.aspx' + '/' + fn,
            contentType: 'application/json; charset=utf-8',
            data: paramList,
            dataType: 'json',
            success: successFn,
            error: errorFn
        });
    };

我正在像这样传递这个方法:

    $(".editableField").keydown(function(e) {

                    WebMethod('PriceContract',
                            [
                             'AQ', aq.val(),
                             'SOQ', soq.val()
                            ], updateTextFields, failed);

        });

C#(注意这些是测试方法,忽略逻辑..)

     [WebMethod]
        public static ContractsListPricing PriceContract(string AQ, string SOQ)
        {
            ContractsListPricing clp = new ContractsListPricing();

           // clp.Aq = nAQ * 2;
           // clp.Soq = nSOQ * 2;

            return clp;
        }

在调试 JS 时, paramList 似乎是正确的 JSON(或者我相信):

{"AQ":"140000","SOQ":"1169"}

这会导致解析错误,我不确定为什么。

任何帮助表示赞赏。

谢谢

4

1 回答 1

1

哦,不,请永远不要像以前那样使用字符串操作来手动构建 JSON。这绝对是可怕的。看看这篇文章

这是正确的方法:

function WebMethod(fn, paramArray, successFn, errorFn) {
    var paramList = { };
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            paramList[paramArray[i]] = paramArray[i + 1];
        }
    }

    $.ajax({
        type: 'POST',
        url: 'ContractView.aspx' + '/' + fn,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(paramList),
        dataType: 'json',
        success: successFn,
        error: errorFn
    });
}

Notice the usage of the JSON.stringify method to properly JSON encode the paramList object. This method is natively built into modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.

于 2012-06-13T11:14:03.053 回答