2012-10-23 199 views
0

我有一個從ajax調用的WebMethod,試圖遍歷返回的數據。正在返回的數據是「{BusinessTypeID = 2}」。我試圖找出如何得到值2?迭代通過JSOn結果

 //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 

    } 
+0

確定返回的數據是不是「{BusinessTypeID:2} 「?如果是這樣,你可以把它作爲targetValue.BusinessTypeID或targetValue ['BusinessTypeID'] –

+0

我已經試過,沒有工作。也許這是我返回數據的方式?我正試圖弄清楚現在.... – user1220099

回答

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) 
}); 

你也可以拋出一個調試器;在警報上方行並查看正在遍歷的值。

0

當您的Web服務返回json值時,asp.net將包裝在一個對象中,其中鍵爲d,值爲您的json字符串。有關更多信息,請查看this link

您必須將值字符串解析爲json對象。使用jQuery(1.4.1或更高版本):

jQuery.parseJSON(targetValue); 
0

你可能要嘗試返回從C#JSON字符串:

public static **string** GetTerminalBusinessTypes(string terminalID) 
... 
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
string sJSON = oSerializer.Serialize(results); 
return sJSON;