2010-06-08 62 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\"}"); 
    }