这个问题已被问及答复很多次,但我不能得到它的工作。我的问题看起来像这样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:我在上面增加了两个注释。 –