2016-05-02 207 views
1

我第一次使用AJAX,我不確定是否有正確的語法。基本上我在後面的代碼中有一個方法,它接受2個字符串參數並執行更新用戶密碼。但它一直失敗。JQuery AJAX請求無法正常工作。

這是我目前的ASP按鈕:

<td><asp:Button ID="Button1" runat="server" Text="Add Password" alt="Add Password" /></td> 

這是執行,一旦用戶點擊窗體上添加密碼按鈕的代碼:

$("#edit_password_form").submit(function (e) { 
         e.preventDefault(); 

         var finalValue = value2.value; 

         <%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%> 
         var custNoString = <%=inputCust%> 

         $.ajax({ 
          url: 'reciept.aspx/Button1_Click', 
          method: 'post', 
          contentType: 'application/json', 
          data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}', 
          success: function(){ 

           alert("The function worked correctly"); 

          }, 
          error:function(){ alert("the function did not succeed");} 
         }); 
        });; 

爲什麼它可能是任何想法失敗? Mayb我缺少一個ajax鍵或者我的語法可能關閉。

讓我知道!謝謝。

+2

請不要將您的數據作爲字符串傳遞,而應將其作爲對象傳遞。 '數據:{custID:custNoString,tempPass2:finalValue}'。 –

+1

備註:考慮使用常規按鈕而不是提交按鈕。在按鈕點擊事件中調用你的函數。這將允許你擺脫'e.preventDefault()'。 –

回答

1

數據參數需要正確創建JSON。你錯過了一些單引號在這裏和那裏。

代替手動創建JSON串,嘗試創建一個對象,然後再字符串化它的數據。請參閱下面的代碼:

$("#edit_password_form").submit(function (e) { 
         e.preventDefault(); 

         var finalValue = value2.value; 

         <%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%> 
         var custNoString = <%=inputCust%> 

         var dataObj = {}; 
         dataObj.custID = custNoString; 
         dataObj.tempPass2 = finalValue; 

         $.ajax({ 
          url: 'reciept.aspx/Button1_Click', 
          method: 'post', 
          contentType: 'application/json', 
          data: JSON.stringify(dataObj), 
          success: function(){ 

           alert("The function worked correctly"); 

          }, 
          error:function(){ alert("the function did not succeed");} 
         }); 
        });; 
+0

好吧,我添加的數據數據:JSON.stringify({custID1:dataObj.custID1,tempPass2:dataObj.tempPass2})這樣的,這會是正確的嗎? – Learn12

1

是不正確的語法發佈數據:data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}'

嘗試通過JSON格式這樣data: { custID: custNoString, tempPass2: finalValue }

否則它不應該工作來傳遞數據。

更多檢查此鏈接http://www.json.org/JSONRequest.html

+0

Nazmul,我需要以json格式的方式使用撇號嗎? – Learn12

+0

必須要得到最好的負擔 –

0

(如發佈代表OP的答案)

這是結束了,我的工作:

// Create the data object for the 2 parameters for the c# Method 

        var dataObj = { custID1: custNoString, tempPass2: finalValue }; 



        // AJAX request for run the function 

        $.ajax({ 

         type: 'post', 

         url: 'reciept.aspx/Button1_Click', 

         contentType: 'application/json; charset=utf-8', 

         data: JSON.stringify(dataObj), 

         success: function(){ 



          alert("The function worked correctly"); 

         }, 

         error:function(){ alert("the function did not succeed");} 

        }); 

創建數據對象首先是關鍵。感謝您的幫助和建議!