0

JSON データと ajax を使用するのはまったく初めてですが、Web サービスから入力したい選択リストがあります。fiddler を使用して、Web サービスが JSON データを正しく返していることを確認しました。選択リストにはデフォルトのみが表示されています----Select-----

Web サービスのコード:

[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 に答える