繁体   English   中英

将字符串从代码传递到ajax

[英]Passing a string from code behind to ajax

我正在服务器端访问方法。 唯一的问题是,我没有大量的AJAx经验。 我无法从.cs方法检索ajax中返回的字符串

$.ajax({
  type: 'GET',
  url: '/frmGpsMap.aspx?name=load',
  dataType: 'text',
  success: function(data) {
    alert(data.d);
  }
});
 protected void Page_Load(object sender, EventArgs e)
        {
            string crrName = Request.QueryString["name"];
            if (!String.IsNullOrEmpty(crrName))
            {
                if (crrName.ToLower().Equals("load"))
                {
                 string fh=   loadKMLFileToString();
                 hdnUsername.Value = fh;
                }
            }
        }

        public string loadKMLFileToString()
        {
            return "hello world";
        }

警报返回页面的html。 我想显示“ Hello World”字符串

为了使方法后面的代码可以使用ajax,您需要使用System.Web.Services.WebMethod。 默认情况下,除非您在后面的代码中指定HTTP GET属性,否则需要使用POST

[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
    return "Hello World";
}

这是调用的ajax方法

$.ajax({
        type: "POST",
        url: "frmGpsMap.aspx/LoadKMLFileToString",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            alert(response.d),
        failure: function(response) {
            alert(response.d);
        }
    });

希望对您有所帮助。 更多示例: http : //weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax

我认为您可以使用WebMethod属性装饰CS方法并直接从ajax调用它。 像这样:

 $.ajax({
  ...
  url: '/frmGpsMap.aspx?loadKMLFileToString',
  ...
});


  [System.Web.Services.WebMethod]
    public string loadKMLFileToString()
    {
        return "hello world";
    }

干杯! =)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM