[英]Passing a string from code behind to ajax
I am accessing a method on the server side. 我正在服务器端访问方法。 The only problem is that I don't have alot of experience in AJAx.
唯一的问题是,我没有大量的AJAx经验。 I am unable to retrieve the returned string in the ajax from the .cs method
我无法从.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";
}
The alert is returning the html of the page. 警报返回页面的html。 I want to display the "Hello World" string
我想显示“ Hello World”字符串
To get the code behind method to work with ajax you need to use System.Web.Services.WebMethod. 为了使方法后面的代码可以使用ajax,您需要使用System.Web.Services.WebMethod。 By default you need to use POST unless you specify HTTP GET attribute in code behind
默认情况下,除非您在后面的代码中指定HTTP GET属性,否则需要使用POST
[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
return "Hello World";
}
Here is the ajax method for call 这是调用的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);
}
});
I hope it helps. 希望对您有所帮助。 More examples: http://weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax
更多示例: http : //weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax
I think you can decorate your cs method with the WebMethod attribute and call it directly from ajax. 我认为您可以使用WebMethod属性装饰CS方法并直接从ajax调用它。 Like this:
像这样:
$.ajax({
...
url: '/frmGpsMap.aspx?loadKMLFileToString',
...
});
[System.Web.Services.WebMethod]
public string loadKMLFileToString()
{
return "hello world";
}
Cheers! 干杯! =)
=)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.