2011-10-14 73 views
1

我有以下的jQuery AJAX請求:jQuery的AJAX調用一個ASP.NET的WebMethod

function sendUpdate(urlToSend) { 
    var code = AccessCode; 
    var url = urlToSend; 
    var options = { error: function(msg) { alert(msg.d); }, 
        type: "POST", url: "webmethods.aspx/UpdatePage", 
        data: "{ accessCode: " + code + ", newURL: '" + url + "' }", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        async: true, 
        success: function(response) { var results = response.d; } }; 
    $.ajax(options); 
} 

和相應的ASP.NET的WebMethod:

[WebMethod] 
public static bool UpdatePage(string accessCode, string newURL) 
{ 
    bool result = true; 
    try 
    { 
     HttpContext.Current.Cache[accessCode + "l"] = newURL; 
    } 
    catch 
    { 
     result = false; 
    } 

    return result; 
} 

這一切都用來與「正常工作async:false「,但是我必須擺脫它,因爲它會凍結瀏覽器直到收到響應。現在上面的AJAX請求返回「undefined」。

有人能告訴我爲什麼會發生,問題在哪裏?

謝謝。

+0

什麼是未定義,「響應」或「response.d」?您應該看到完整的響應對象是看看它是否給出了來自服務器的任何錯誤消息。 – rossisdead

回答

5

你應該確保正確編碼這個JSON。 JSON.stringify是最可靠的方法:

data: JSON.stringify({ accessCode: code, newURL: url }) 

這保證了即使codeurl變量包含一些危險的字符,這將打破你的字符串串聯在年底的一切所產生的JSON將被正確編碼。 JSON.stringify方法自然適用於現代瀏覽器,但如果您需要支持遺留代理,則可以包含json2.js

也因爲你的代碼不再阻塞你應該確保如果你從某個按鈕點擊或表單提交時調用這個sendUpdate你通過返回false來取消默認動作。

0

「未定義」可能是服務器錯誤的結果。如果使用Firebug,Firefox(或任何良好的客戶端調試工具),則可以找到服務器返回的錯誤。粘貼錯誤,如果有的話。

不過,我也注意到了 「數據」 爲 「accessCode」 引號內沒有正確封閉‘ ’

校正數據的辦法是:

data: "{ accessCode: '" + code + "', newURL: '" + url + "' }", 

PS: 由於「選項'在Jquery中有不同的含義,我建議將變量名改爲'setting'。將'var options'更改爲'var settings'。 :)

1

我的方式正常工作:

[System.Web.Services.WebMethod()] 

     public static string getHello(string str) 
     { 
      //do some things with str 
      return str; 
     } 

在文件的.js,我定義這個函數調用的webmethod文件的.cs:

function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) { 

    $.ajax({ 
     type: "post", 
     url: StrPriUrl, 
     contentType: "application/json; charset=utf-8", 
     data: ObjPriData, 
     dataType: "json", 
     success: function (result) { 
      if (CallBackFunction != null && typeof CallBackFunction != 'undefined') { 
       CallBackFunction(result); 
      } 

     }, 
     error: function (result) { 
      alert('error occured'); 
      alert(result.responseText); 
      window.location.href = "FrmError.aspx?Exception=" + result.responseText; 
     }, 
     async: true 
    }); 
} 

然後,調用使用(在文件中調用。 js):

var text = $("#textbox_send").val(); 

    var myresult; 
    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) { 
     if (text != "") 
      $('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>'); 
    });