我有一個asp.net MVC網站,其引導模式有一個reCaptcha形式。它在提交時正確地驗證了輸入,但是如果它無效,則在呈現視圖以便他們可以再次嘗試時,驗證碼消失並且javascript控制檯顯示此錯誤:「在'Document'上執行'write'失敗:它不是'除非明確打開,否則可以從異步加載的外部腳本寫入文檔。「我必須刷新頁面並重新打開模式以再次查看驗證碼。如何在失敗的輸入後保持屏幕上的reCaptcha
的片段包含圖形驗證碼(公鑰/私鑰是在web.config中):
<input type="hidden" name="ProductID" value="@Model.ProductID" />
<input type="hidden" name="UserTypeID" value="@Model.User.UserTypeID" />
@Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
<div id="request-error-summary">
@Html.ValidationSummary(false, "All fields are required.")
</div>
在提交表單控件代碼:
public PartialViewResult SubmitRequest(RequestKitModel kitModel)
{
/* code removed for brevity */
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
ModelState.AddModelError("", "Captcha answer cannot be empty.");
return PartialView("_Request", kitModel);
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
ModelState.AddModelError("", "Incorrect captcha answer.");
return PartialView("_Request", kitModel);
}
/* code to ruun upon success of captcha input */
//close modal and return to results
return PartialView("_Confirmation");
}
jQuery的Ajax調用SubmitRequest ...我認爲我加載局部視圖的方式可能是罪魁禍首。
if ($('#request-form').valid()) {
$.ajax({
url: "/SubmitRequest",
type: "POST",
data: $("#request-form").serialize(),
success: function (data) {
//show the confirmation (thanks) modal
$("#request-modal .modal-content").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
window.location.href = '@Url.Action("Error")';
}
});
}
更新:我將它更改爲使用recaptcha_ajax.js,因爲我在ajax請求後加載它。現在我得到這個錯誤:「無法從recaptcha_ajax.js文件中設置屬性'innerhtml'的null」(不能告訴哪個對象拋出此錯誤)。相反,在剃刀文件調用Html.Recaptcha的,我現在有這樣的:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha1"></div>
和更新的AJAX調用:
$.ajax({
url: "/SubmitRequest",
type: "POST",
data: $("#request-form").serialize(),
success: function (data) {
//show the confirmation (thanks) modal
$("#request-modal .modal-content").html(data);
Recaptcha.create("6LedL_sSAAAAAJuozIfRiVfNOCHs-jlTn6NM4c-T",
"recaptcha1",
{
theme: "white",
callback: Recaptcha.focus_response_field
}
);
console.log("done loading html");
console.log('captcha control: ' + $("#recaptcha1").length);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
window.location.href = '@Url.Action("Error")';
}
});
最後我把所有的代碼了,因爲它結束了不被需要。因此,考慮到自發布以來的時間長度,我無法輕鬆地嘗試這一點(儘管當時我確實添加了recaptcha_ajax.js庫,但可能不在正確的位置?)。不知道是否適當的協議是刪除帖子 – Kelly 2015-07-29 13:12:40
嗨凱利,NP我認爲我們可以離開它也許它會幫助別人? – salvador 2015-08-03 18:54:33