我正在使用javascript方法进行jquery调用。我想要一个参数发送到我的回调方法。我正在使用一个处理程序(ashx)进行jquery调用,处理程序被调用,但回调没有被触发。 以下是代码
function MyButtonClick(){
var myDiv = "divname";
$.post("MyHandler.ashx", { tgt: 1 }, myDiv, CustomCallBack);
}
function CustomCallBack(data, result) {
debugger;
//SomeCode
}
}
处理程序代码(ashx文件)
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int tgt = Convert.ToInt32(context.Request["tgt"]);
if (tgt == 1)
{
context.Response.Write("Some text");
}
}
答案 0 :(得分:0)
您是否看过这个页面:http://docs.jquery.com/How_jQuery_Works#Callback_with_arguments
你是否应该使用$ .get(... call?
$.get("MyHandler.ashx", { tgt: 1 }, myDiv, function() {
CustomCallBack(data, result);
});
答案 1 :(得分:0)
在你的ashx中,你需要从阅读后期数据中获取数据......
StringBuilder HttpInputStream;
public void ProcessRequest(HttpContext context)
{
HttpInputStream = new StringBuilder();
GetInputStream(context);
// the data will be in the HttpInputStream now
// What you might want to do it to use convert it to a .Net class ie,
// This is using Newtonsoft JSON
// JsonConvert.DeserializeObject<JsonMessageGet>(HttpInputStream.ToString());
}
private void GetInputStream(HttpContext context)
{
using (Stream st = context.Request.InputStream)
{
byte[] buf = new byte[context.Request.InputStream.Length];
int iRead = st.Read(buf, 0, buf.Length);
HttpInputStream.Append(Encoding.UTF8.GetString(buf));
}
}
在您的回复中,调用者 - 您的ashx需要以JSON响应,以便调用者JavaScript可以使用它。
我建议使用Newstonsoft JSON,例如......
public void ProcessRequest(HttpContext context)
{
// read from stream and process (above code)
// output
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(JsonConvert.SerializeObject(objToSerialize, new IsoDateTimeConverter()));
}
或者使它真的很容易,改为 - 基本上需要用JSON回复JavaScript处理程序来处理它
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{data:\"Reply message\"}");
}