2011-12-08 60 views
0

是否有可能從從JavaScript調用一個webmethode檢索值或日期,這裏是一個示例代碼:從JavaScript調用JavaScript從webservice檢索值?

//This method is in a webservice.asmx file. 
[WebMethod] 
public List<tbl_City> GetAllCitiesByCountry(int countryID) 
{ 

    return Cities.GetAllCitiesByCountry(CountryID: countryID); 
} 


<script language="javascript" type="text/javascript"> 

function fillCities() { 
    var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>'); 
    var selectedIndex = dropDownList.selectedIndex; 
    var value = dropDownList[selectedIndex].value; 

    WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, ""); 

} 

    function onSuccess(result){ 
     alert(result[0].(PropertyName)); 
     } 

變量x不檢索任何東西,我猜測它產生錯誤。我試圖定義一個數組,但仍然無法工作。任何想法 ?

編輯:

上面的代碼已經改變,現在是回答我的問題與低於使用JQuery的答案一起。

回答

2

使用JSON響應簡單。

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class CitiService : WebService 
{ 
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<tbl_City> GetAllCitiesByCountry(int countryID) 
    { 
    List<tbl_City> cities = GetCities(countryID); 
    JavaScriptSerializer js = new JavaScriptSerializer(); 
     var jsonObj = js.Serialize(cities); 
     Context.Response.Clear(); 
     Context.Response.Write(jsonObj); 
     Context.Response.End(); 
    } 
} 
ASp.net頁面上

<script language="javascript" type="text/javascript"> 
$.ajax({ 
     url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>', 
     dataType: "json", 
     data: "{countryID:'100'}", 
     success: function (result) { 
      alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid 
     } 
     }); 

+0

上的WebMethod的第三行,提示錯誤做到這一點很容易:無法訪問處置的對象。 對象名稱:'在Dispose之後訪問DataContext'。 –

+0

我解決了這個問題,事實證明DataContext在使用結束後自行處理它。 –

+0

你不需要手動JSON序列化。如果你只返回'cities',ASP.NET將自動處理通過JavaScriptSerializer爲你運行它。更多信息:http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/ –

1

你可以用jQuery和ASP.NET webMethods的Encosia