从javascript调用的web服务中检索值

Retrieve value from webservice called from javascript?

本文关键字:检索 服务 web javascript 调用      更新时间:2023-09-26

是否可以从javascript中调用webmethode来检索值或日期,这里有一个示例代码:

//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的答案。

使用Jquery的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
        }
      });

您可以使用JQuery和ASP轻松地做到这一点。. NET webmethods Encosia

您需要向ScriptManager注册您的web服务,然后从客户端调用它。看看这个教程:

使用AJAX扩展的客户端Web服务调用

你也可以使用jQuery的web服务,但在这种情况下,你需要切换到JSON:从jQuery调用ASMX