【问题标题】:Data from the Form Submit vs Data from Ajax来自表单提交的数据与来自 Ajax 的数据
【发布时间】:2015-02-23 13:12:00
【问题描述】:

我正在尝试在我的 MVC 站点中实现 reCAPTCHA,但除非我从表单提交它,否则它不会验证,如下所示:

    @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();
    }

我不想使用表单提交,因为我不想返回新视图。我所有的数据都被 ajax 以 json 形式推送。我想做的是:

$.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 调用到达控制器,但 Validation 方法立即完成,就好像它甚至没有发出请求一样。如果验证码不在表单中,我不确定为什么验证总是失败 - 是否可能会丢失诸如公钥之类的信息?有解决办法吗?

编辑:添加了没有模型的 ajax 控制器操作方法。

【问题讨论】:

  • 将按钮类型更改为按钮并在您的 ajax 中分配一个有效的 url,在您的按钮单击事件中编写 ajax
  • 所以你在你的ajax代码中设置了type : 'POST'?将您的代码置于完成状态更容易为您提供帮助
  • 好的,你的ajax请求到达Action还是没有?
  • 是的,确实如此。我有一种感觉,它丢失了公钥或其他东西,因为它总是返回 false,如此之快以至于它似乎甚至没有提交请求。
  • 您必须将数据属性中的公钥作为 json 发送

标签: javascript jquery ajax asp.net-mvc forms


【解决方案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);
        }
});

您尚未在请求中添加数据部分。好像是这个问题

【讨论】:

  • 你先生,是让我的星期一可以忍受的人。完美运行 - 非常感谢!您能否解释一下为什么我实际上需要将表单作为数据传递?
  • 原因很简单。您需要data 来验证请求。但是由于您希望它作为表单响应,您需要构建数据对象并通过 AJAX 发送它。由于您使用的是 jQuery,因此您可以使用内置功能从表单中获取数据。
【解决方案2】:

您需要使用表单请求的所有参数设置 Ajax 请求。例如内容类型为application/x-www-form-urlencoded

看看这个:application/x-www-form-urlencoded or multipart/form-data?

更新:
...是的 ...您必须执行 POST 请求,而不是 GET。

更新:

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

【讨论】:

  • 好的,刚刚看到你编辑了。它更完整但仍然错误:尝试使用content-type: "application/x-www-form-urlencoded"
  • 好的,我做到了。还是个问题。
  • 查看alert('ERROR', response); 显示的内容。在response 中有错误代码,然后您可以找到有关该问题的更多信息。
  • 我的 ajax 调用没有任何问题。 Validate 的服务器端调用总是返回 false。
猜你喜欢
  • 2018-03-15
  • 2018-03-13
  • 2020-07-31
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
相关资源
最近更新 更多