这个问题已被多次询问和回答,但我无法让它发挥作用。我的问题看起来像这个,这个和第三个例子。
我想做的是从这个和这个问题中的 JSON 对象填充一个选项框。它们都略有不同,但相似,但我无法让它工作。这是我来自网络服务的代码:
<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}]
这似乎没问题。
如果我从味精中删除“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 对象。(这不是“数据类型”的用途吗?)我不能使用命名对象,因为我没有你在示例数据中看到的那样。我错过了什么?
有些我无法让代码看到数组有三个条目。