2013-10-28 181 views
0

這個問題已被問及答覆很多次,但我不能得到它的工作。我的問題看起來像這樣one,這onethird example迭代通過JSON對象數組

我想要做的是從JSON對象填充一個選項框,如thisthis問題。他們都略有不同,但相似,但我無法實現它的工作。下面是從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對象。 (是不是'數據類型'的目的?)我不能使用命名對象,因爲我沒有,就像你可以在示例數據中看到的那樣。我錯過了什麼?

一些如何我不能讓代碼看到數組有三個條目。

回答

0

我可能會使用Option構造函數,而不是HTML。

假設msg.d是真正的陣列(即.d屬性是一個ASP.Net的東西):

success: function (msg) { 
    var options = $("#prd_id")[0].options; 
    options.length = 0; 
    options.add(new Option("Please select", "[-]")); 
    $.each(msg.d, function() { 
     options.add(new Option(this.Productname, this.Id)); 
    }); 
}, 

Live Example | Source

構造函數Option將文本作爲第一個參數,將值作爲第二個參數。 select元素上的options列表有點像數組,但爲了與舊版瀏覽器兼容,而不是push,請使用add(或分配給options[options.length],或者工作正常)。

或者,如果msg是陣列(無.d),只是刪除.d

success: function (msg) { 
    var options = $("#prd_id")[0].options; 
    options.length = 0; 
    options.add(new Option("Please select", "[-]")); 
    $.each(msg, function() { 
     options.add(new Option(this.Productname, this.Id)); 
    }); 
}, 

Live Example | Source

如果您的回覆沒有以正確的MIME類型發回,msg實際上可能是文本,而不是數組。如果是這樣,你想通過返回正確的MIME類型(application/json)修復服務器上,儘管你可以手動解析它:

msg = $.parseJSON(msg); 

...然後用以上。或者,當然,如果它要回來爲msg.d(儘管這似乎真的不太可能):

msg.d = $.parseJSON(msg.d): 
+0

從你的活生生的例子,我可以看到「d」是一個命名對象。從webservice中我的消息中不存在。這解釋了爲什麼它不起作用。在你的例子中任何方式你使用'd',所以這是行不通的。真的很酷,你創造了一個現場例子,但速度如此之快。 – Sigur

+0

@Sigur:你說你提醒了'msg.d'並得到了,所以我認爲'msg.d'是數組(這是ASP.Net所做的,我從來不明白爲什麼)。如果'msg'是數組,只需刪除'.d'。 –

+0

@Sigur:我在上面增加了兩個註釋。 –

0

你可以這樣做:

$.each(msg.d, function (key, value) { 
    $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname)); 
}); 

Fiddle Demo

+0

@Palash見我的回答對TJ克羅德上述 – Sigur

0

我想根據我的REST WCF您的問題,它返回相同的JSON數據複製,以及下面的示例工作,

<script type="text/javascript"> 
$(document).ready(function() { 
}); 
var GetRawList = function() { 
    $.ajax({ 
     type: "GET", 
     url: "RestService/HelloWorld", 
     contentType: "application/json;charset=utf-8", 
     dataType: "json", 
     success: function(data) { 
    //Change this "data.d" According to your returned JSON output header. 
      var result = data.d; 
    $("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select")); 
      $.each(result, function(key, value) { 
      $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname)); 
      }); 
     }, 
     error: function(xhr) { 
      alert(xhr.responseText); 
     } 
    }); 
} 

+0

我試過你的代碼。結果是我以前見過的東西:一個非常長的選項列表,沒有文字。如果我刪除了'd',那麼有一個列表選項不帶任何特技。在TJ Crowder的評論之後,我調查了一下。我正在使用我的新僱主定製的框架,我的任務是學習它。該框架似乎與.asmx相關的東西做了一些事情。爲了使這個工作,我打算使用WCF服務,看看會發生什麼。謝謝 – Sigur