2015-02-23 51 views
0

我想在我的MVC的網站使用reCAPTCHA,但它不驗證,除非我從一個表單提交,就像這樣:提交數據VS數據從阿賈克斯

@using(Html.BeginForm("VerifyCaptcha", "Signup")) 
    { 
     @ReCaptcha.GetHtml(theme: "clean", publicKey: "6LcnfAITAAAAAAY--6GMhuWeemHF-rwdiYdWvO-9"); 
     <input type="submit" id="btnVerify" value="Verify" /> 
    } 

    [HttpPost] 
    public ActionResult Index(PolicyModel model) 
    { 
     var result = ReCaptcha.Validate(privateKey: "THE_KEY"); 
     return View(); 
    } 

我不不想使用表單提交,因爲我不想返回新的視圖。我所有的數據都以json形式被ajax推送。我想要做的是:

$.ajax({ 
    url: 'verifyCaptcha', 
    dataType: 'json', 
    contentType: "application/x-www-form-urlencoded", 
    type: "POST", 
    async: false, 
    success: function (response) { 
     alert(response); 
    }, 
    error: function(response) { 
     alert('There was a problem verifying your captcha. Please try again.'); 
    } 
}); 
return valid; 

     [HttpPost] 
     public ActionResult VerifyCaptcha() 
     { 
      var result = ReCaptcha.Validate(privateKey: "THE_KEY"); 

      return Json(result); 
     } 

AJAX調用獲取到控制器,但驗證方法立即完成,彷彿它甚至沒有得到提出要求。我不確定爲什麼驗證總是失敗,如果驗證碼不在表單中 - 它是否會丟失信息,如公鑰或什麼?有沒有解決這個問題的方法?

編輯:添加了沒有模型的ajax控制器操作方法。

+0

更改按鈕類型爲按鈕,並在您的ajax分配一個有效的網址,在您的按鈕單擊事件 – 2015-02-23 13:16:11

+0

內寫入ajax,所以你在你的ajax代碼中設置'type:'POST''?讓你的代碼處於完成狀態,更容易幫助你 – sabotero 2015-02-23 13:22:21

+0

ok,你的ajax請求到達'Action'或者沒有? – sabotero 2015-02-23 13:23:41

回答

1

只需使用serializeArray()serialize(),改變你的Ajax請求

$.ajax({ 
    url: 'verifyCaptcha', 
    dataType: 'json', 
    contentType: "application/x-www-form-urlencoded", 
    type: "POST", 
    async: false, 
    data: $('form').serializeArray(), // $('form').serialize(), 
    success: function (response) { 
      alert(response); 
     } 
}); 

你還沒有添加在您的請求中的數據部分。這似乎是問題

+0

您好,先生,是讓我的星期一可以忍受的人。完美地工作 - 非常感謝!你可能會對我爲什麼需要將數據作爲數據傳遞給我們一些啓示嗎? – 2015-02-23 13:42:12

+1

簡單的原因。您需要'數據'來驗證請求。但是,既然你想將它作爲表單響應,你需要構建你的數據對象並通過AJAX發送它。而且,由於您使用的是jQuery,因此您可以使用內置功能從表單中獲取數據。 – 2015-02-23 14:42:05

0

您需要爲表單請求設置包含所有參數的Ajax請求。例如內容類型爲application/x-www-form-urlencoded

看看這個:application/x-www-form-urlencoded or multipart/form-data?

UPDATE:
...是...你必須做一個POST請求,而不是GET。

UPDATE:

$.ajax({ 
    url: 'verifyCaptcha', 
    contentType: "application/x-www-form-urlencoded", 
    type: "POST", 
    success: function (response) { 
     alert(response); 
    }, 
    error: function(response) { 
     alert('ERROR', response); 
    } 
}); 
+0

請參閱我的編輯。實際的ajax代碼是完整的。問題是別的... – 2015-02-23 13:23:18

+0

好吧,只是看到你編輯。這是更完整的,但仍然是錯誤的:嘗試與'content-type:「application/x-www-form-urlencoded」' – RikyTres 2015-02-23 13:26:52

+0

好吧,我做到了。仍然是一個問題。 – 2015-02-23 13:30:10