AJAX 表单提交命中正确的终结点,但不传递变量

AJAX form submission hits proper endpoint but doesn't pass variables

本文关键字:变量 结点 表单提交 AJAX      更新时间:2023-09-26

在用户购买产品之前,我正在评论页面上工作,页面上有一个折扣代码的小字段,我想通过 ajax 将其传递给端点。我正在使用以下 javascript 函数,提交发生并返回(甚至命中预期的端点( - 但没有数据通过(在日志中验证(。

知道为什么没有参数会通过吗?

    <script>
  $("#discount_code_submit").click(function() {
    var url = "/confirm_discount"; // the script where you handle the form input.
    $.ajax({
           type: "POST",
           url: url,
           data: $("#discount_form").serialize(), // serializes the form's elements.
           success: function(data)
           {
                alert(data); // show response 
                if(data != "false")
                {
                    console.log(data);
                }
           }
         });
    return false; // avoid to execute the actual submit of the form.
});
</script>

这是因为 jQuery 的序列化方法以传统的 url 查询字符串格式创建表单数据的 String 表示形式。(请看这里: http://api.jquery.com/serialize/(
例如,调用 serialize 可以返回一个字符串,例如:

'?query=help&numResults=200'


另一方面,jQuery的ajax方法期望表单数据作为对象文字提供。(请看这里:http://api.jquery.com/jQuery.ajax/(
例如

{
   query: 'help',
   numResults: 200
}

因此,您可以将 ajax 调用更改为如下所示:

$.ajax({
       type: "POST",
       url: url,
       data: {
           param1: 'somevalue',
           param2: 200
       },
       success: function(data)
       {
            alert(data); // show response 
            if(data != "false")
            {
                console.log(data);
            }
       }
});

或者,您也可以使用自定义函数从窗体构造对象文本,然后在 ajax 调用中提供引用。

$.ajax({
       type: "POST",
       url: url,
       data: myPreparedObjectLiteral,
       success: function(data)
       {
            alert(data); // show response 
            if(data != "false")
            {
                console.log(data);
            }
       }
});

您也可以使用 http://api.jquery.com/serializeArray/因为它几乎可以完成将表单转换为 json 文字表示所需的功能。

最后,关于将表单转换为 json 对象进行发布的重要讨论,您可以在此处查看有关 SO 问题的回答:使用 jQuery 将表单数据转换为 JavaScript 对象