0

我对使用 JSON 数据和 ajax 完全陌生,但我有一个要从 Web 服务填充的选择列表。我使用 fiddler 来查看 Web 服务是否正确返回 JSON 数据,并且我验证了它是正确的。选择列表仅显示默认值----Select-----

网络服务的代码:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

 [ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    private TrackerEntities db = new TrackerEntities();


    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetCompanies()
    {
        var companies = new List<Company>();
        companies = (from c in db.Ref_Company
                     select new Company { CompanyDesc =  c.CompanyDesc,CompanyCode = c.CompanyCode }).ToList();
        return new JavaScriptSerializer().Serialize(companies);
    }


}

public class Company
{
    public string CompanyCode { get; set; }
    public string CompanyDesc { get; set; }
}

HTML 代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>   
<script type="text/javascript">
 $(document).ready(function () {
     $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         data: "{}",
         url: "WebService1.asmx/GetCompanies",
         dataType: "json",
         success: ajaxSucceess,
         error: ajaxError
     });
     function ajaxSucceess(data) {
        $.each(data, function (index, elem) {
           // Create a new <option>, set its text and value, and append it to the <select>
           $("<option />")
              .text(elem.CompanyCode)
              .val(elem.CompanyDesc)
              .appendTo("#Select1");
        });
     }

     function ajaxError(response) {
         alert(response.status + ' ' + response.statusText);
     }
 });


</script>   
</head>
<body>
<form id="form1" runat="server">


 <select id="Select1"><option>---Select------</option></select>


</form>
</body>
</html>
4

1 回答 1

0

Based on the comments above, I think the issue is that you're not accessing the array properly. Considering this JSON response:

{ "d" : "[
  { "CompanyCode" : "HTH", "CompanyDesc" : "Company1" },
  { "CompanyCode" :‌ "SMC", "CompanyDesc" : "Company2" },
  { "CompanyCode" : "CTT", "CompanyDesc" : "‌​Company3" }
]"}

If this is the value of data in your success function in the JavaScript code, then you can't loop through data as an array. Because data isn't an array, it's a single object. That object contains an array, in a property called d. Try changing your call to $.each() to use that property instead:

$.each(data.d, function (index, elem) {
    //...
});

You might even test it with a normal for loop to make sure:

for (var i = 0; i < data.d.length; i++) {
    // do something with data.d[i]
}
于 2013-09-16T16:56:55.200 回答