将代码中的字符串传递给ajax

Passing a string from code behind to ajax

本文关键字:ajax 字符串 代码      更新时间:2023-09-26

我正在访问服务器端的一个方法。唯一的问题是我在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。默认情况下,您需要使用POST,除非在

后面的代码中指定HTTP GET属性。
[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";
    }

干杯!div =)