2016-12-27 18 views
0

我在後面的代碼中定義了一個webMethod,如下所示。使用參數作爲本地變量的Ajax調用不起作用

[System.Web.Services.WebMethod] 
     public static string testCall(int qid, String answerContent) 
     { 
     log.Debug("this is call from jquery" + qid.ToString() + answerContent); 

      return "true"; 
     } 

我想通過調用jQuery中的ajax調用此方法如下。

<script> 

     $(".submitBtn").click(function (e) { 

      alert(this.id); 
      var qID = this.id; 

      $.ajax({ 
       type: "POST", 
       url: '/default.aspx/testCall', 
       data: '{ "qid":' + qID + ', "answerContent":"test" }', 
       contentType: "application/json; charset=utf-8", 
       success: function() { 

       }, 
       failure: function (response) { 
        alert("fail"); 
       }, 
       dataType: 'html' 
      }); 
     }); 
      </script> 

但是這不起作用。

但是,我通過硬編碼參數值如下,它工作正常。

data: '{ "qid":"1234", "answerContent":"test" }' 

但隨着var qID傳遞作爲參數不工作

+0

用'data:JSON.stringify({「qid」:qID,「answerContent」:「test」})測試一次' – Satpal

+0

我假設您正在使用Webforms嗎? – Valkyrie

+0

@Valkyriee是的。 –

回答

1

不要用手組裝JSON。您將通過文字得到咬傷你不串想到,你就會錯過分隔符等

相反,使用JSON stringifier:

data: JSON.stringify({qid: qID, answerContent:"test"}), 

如果ID值是一個真正的數字(您收到它作爲一個int),你要分析它(作爲this.id是一個字符串):

data: JSON.stringify({qid: +qID, answerContent:"test"}), 
// ------------------------^ 

...但你說你的作品硬編碼例子使用了字符串的ID,所以...

+0

試過這個..仍然沒有工作。 –

+0

我已經發布了我正在使用的所有內容。在服務器端硬編碼的值「1234」可以解析爲int,可能是多數民衆贊成爲什麼它的工作。但是,我想傳遞這個不適合我的this.id。 –

+0

好吧,我碰到它。 「this.id」沒有整數值,這就是爲什麼它失敗。我很抱歉。我改變參數類型爲字符串,它的工作。謝謝你的幫助。 –

1

你應該使用這條線:

data: '{ "qid": "' + qID + '", "answerContent":"test" }' 
+0

不,他真的不應該。 –

+0

它不工作。 –