這個問題已被問及答覆很多次,但我不能得到它的工作。我的問題看起來像這樣one,這one和third example。迭代通過JSON對象數組
我想要做的是從JSON對象填充一個選項框,如this和this問題。他們都略有不同,但相似,但我無法實現它的工作。下面是從WebService我的代碼:
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function HelloWorld(ByVal p_productCategoryId As Integer) As String
Dim productCategory = ProductService.GetProductCategory(p_productCategoryId)
'Dim productList = ProductService.GetProducts(productCategory)
Dim productList = New List(Of Product)
For cnt = 1 To 3
Dim product = New Product(cnt)
product.Productname = cnt.ToString & "|" & cnt.ToString
productList.Add(product)
Next
Return productList.ToJSON
End Function
End Class
<System.Runtime.CompilerServices.Extension()> _
Public Function ToJSON(Of T)(p_items As List(Of T)) As String
Dim jSearializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Return jSearializer.Serialize(p_items)
End Function
如果我使用下面的代碼:
function Test() {
$.ajax({
type: "POST",
url: "Service.asmx/HelloWorld",
data: "{'p_productCategoryId' : 1 }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(msg){
alert(msg.d)
},
error: function() {
alert("An error has occurred during processing your request.");
}
});
};
我得到這樣的結果:
[{"Id":1,"IsActive":false,"Category":null,"Productname":"1|1","Price":0},
{"Id":2,"IsActive":false,"Category":null,"Productname":"2|2","Price":0},
{"Id":3,"IsActive":false,"Category":null,"Productname":"3|3","Price":0}]
這似乎確定。
如果我從msg中刪除'd'。在警報結果是:
[object Object]
的「工作進行中」代碼來填充選項框是這樣(目前:):
function Test() {
$.ajax({
type: "POST",
url: "Service.asmx/HelloWorld",
data: "{'p_productCategoryId' : 1 }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function() {
$("#prd_id").append($("<option></option>").val(this['Id']).html(this['Productname']));
});
},
error: function() {
alert("An error has occurred during processing your request.");
}
});
};
我已經嘗試了幾種方法來從我之前提到的例子中獲得它,但無濟於事。使用msg.d填充字符串中字符數量的選項框。我試圖用'getJSON'從'msg'顯式創建一個JSON對象。 (是不是'數據類型'的目的?)我不能使用命名對象,因爲我沒有,就像你可以在示例數據中看到的那樣。我錯過了什麼?
一些如何我不能讓代碼看到數組有三個條目。
從你的活生生的例子,我可以看到「d」是一個命名對象。從webservice中我的消息中不存在。這解釋了爲什麼它不起作用。在你的例子中任何方式你使用'd',所以這是行不通的。真的很酷,你創造了一個現場例子,但速度如此之快。 – Sigur
@Sigur:你說你提醒了'msg.d'並得到了,所以我認爲'msg.d'是數組(這是ASP.Net所做的,我從來不明白爲什麼)。如果'msg'是數組,只需刪除'.d'。 –
@Sigur:我在上面增加了兩個註釋。 –