0

我有一个从 ajax 调用的 WebMethod,试图遍历返回的数据。返回的数据是“{ BusinessTypeID = 2 }”。我试图弄清楚如何获得价值2?

        //Function called from ajax
[System.Web.Services.WebMethod]
public static string[] GetTerminalBusinessTypes(string terminalID)
{
    DataClassesDataContext db = new DataClassesDataContext();
    List<string> results = new List<string>();

    try
    {

        var terminalBusinessTypes = (from bt in db.BusinessTypes
                                    join obt in db.OxygenateBlenderBusinessTypes on bt.BusinessTypeID equals obt.BusinessTypeID
                                    where obt.OxygenateBlenderID == Convert.ToInt32(terminalID)
                                    select new
                                    {
                                        bt.BusinessTypeID
                                    }).ToList();


        for (int i = 0; i < terminalBusinessTypes.Count(); i++)
        {
            results.Add(terminalBusinessTypes[i].ToString());
        }

    }
    catch (Exception ex)
    {

    }

    return results.ToArray();
}

ajax函数:

            function PopulateTerminalBusinessTypes(terminalID) {

        $.ajax({
            type: "POST",
            url: "OxygenateBlenderCertificationApplication.aspx/GetTerminalBusinessTypes",
            data: "{'terminalID':" + terminalID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                var targetValue = data.d;

                var items = $('#cblTerminalBusinessType input:checkbox');



                                    $.each(targetValue, function (key, targetValue) {
                                        alert(data[index].BusinessTypeID);
                                    });
                    }
        })//end ajax

    }
4

3 回答 3

0

当您的 Web 服务返回 json 值时,asp.net 将包装在一个对象中,其中键d是您的 json 字符串,值是您的 json 字符串。查看此链接以获取更多信息。

您必须将值字符串解析为 json 对象。使用 jQuery(v1.4.1 或更高版本):

jQuery.parseJSON(targetValue);
于 2012-10-23T19:34:31.283 回答
0

您可能想尝试从 C# 返回 JSON 字符串:

public static **string** GetTerminalBusinessTypes(string terminalID)
...
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(results);
return sJSON;
于 2012-10-23T20:08:13.530 回答
0

老实说,我看不到您的“索引”是在哪里定义的。

不应该读取警报行

$each(targetVale, function(key, item) {
   // on second look, this wont work as you are converting toString()
   alert(targetValue[key].BusinessTypeId)
   // this should
   alert(item)
});

你也可以抛出一个调试器;警报上方的行并查看正在遍历的值。

于 2012-10-23T19:32:39.477 回答