以下ajax请求有效。但是,它并不理想。事实证明,HttpContext很难处理。 Context.Response.Clear()绝对没有。
如何在没有额外信息的情况下将输出内容写入输出?
此外,我希望这个ajax请求直接访问RetrieveAddress类,但取消注释URL参数会给我一个HTTP 500错误。所以现在,ajax请求只是访问代码隐藏(IsPostBack是假的......)
让ajax只访问一种方法的正确语法是什么?
function showLocation(position) {
$.ajax({
type: "POST",
//url: "ThisLocation.aspx/RetrieveAddress",
//contentType: "application/json; charset=utf-8",
data: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
//datatype: "JSON",
success: function (msg) {
address1 = document.getElementById('address');
//my illegitimate hack to retrieve only what I inserted
address1.value = msg.substr(0, msg.indexOf('\n'));
}
});
}
这是代码隐藏。截至目前,有效的方法是在Page_Load方法中。我无法使RetrieveAddress方法起作用。
public partial class ThisLocation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Common.CheckAnyLogin();
//if we're coming from ajax request
if (Context.Request["latitude"] != null && Context.Request["longitude"] != null)
{
double lat;
double long;
lat = Double.Parse(Context.Request["latitude"].ToString());
long = Double.Parse(Context.Request["longitude"].ToString());
//can i access this session from html after initial load?
Session["MyLocAddress"] = GetAddress.GetAddressAll(lat, long);
// Why doesn't this actually clear anything?
Context.Response.Clear();
Context.Response.Write(Session["MyLocAddress"].ToString());
}
}
public static string RetrieveAddress(double latitude, double longitude)
{
return GetAddress.GetAddressAll(latitude, longitude);
}
}
答案 0 :(得分:0)
由于您对ASPX页面使用POST,因此需要将该方法作为请求参数包含,而不是URL的一部分。在您的Ajax请求中:
data: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
method: "RetrieveAddress"
}
然后在codebehind:
if (Context.Request["method"] == "RetrieveAddress")
{
Callyourmethod();
}
繁琐。这就是我使用Web服务而不是ASPX页面的原因。使用Web服务,您可以直接从Ajax访问这些方法。
答案 1 :(得分:0)
你缺少的Response.End(),从技术上讲,这应该有用......
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Write("Hello");
Response.End();
}
另外,要直接访问该方法,必须使用[WebMethod] 属性...
[WebMethod]
public static string RetrieveAddress(double latitude, double longitude)
{
return GetAddress.GetAddressAll(latitude, longitude);
}