2010-06-08 85 views
2

我正在从javascript方法进行jquery调用。我想要一个参数发送到我的回调方法。我正在使用处理程序(ashx)来进行jquery调用,处理程序正在被调用,但回调没有被触发。 下面是代码发送参数到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

你吃过看看这个页面:http://docs.jquery.com/How_jQuery_Works#Callback_with_arguments

如果你要使用$不用彷徨(..电话?

$.get("MyHandler.ashx", { tgt: 1 }, myDiv, function() { 
     CustomCallBack(data, result); 
    }); 
+0

汗是使用C#不是PHP – 2010-06-08 08:32:11

+1

嗨@Jason不是PHP。 JQuery的。这个问题不清楚哪个处理程序没有被调用。 MyHandler.ashx或回调处理程序。猜测它是ashx处理程序。我会修改这个问题,使之更加清晰。 – 2010-06-08 08:39:01

+0

它不能正常工作 – KhanS 2010-06-08 09:27:38

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\"}"); 
    }