【问题标题】:How to send html form data with jquery如何使用 jquery 发送 html 表单数据
【发布时间】:2015-12-17 20:19:18
【问题描述】:

我想用用户填写的 html 表单中的数据发送 post 请求。我想使用 jquery 来实现这一点。这是我的尝试(不工作):

$(function () {
    $("#create").click(function (event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "/home/new",
            data: $(this).serialize(),
            success: function (data, textStatus, jqXhr) {
                //call "home/new" with data from html form as json and update current view with returned data
                console.log("success");
            },
            error: function () {
                alert("error");
            }
        });
    });
});

<html lang="en">
<head>
    <script type="text/javascript" src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/Helpers.js"></script>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Title Goes Here</title>
</head>

<body>
    <form>
        Note:<br>
    </form>
    <textarea rows="4" cols="50" name="note" form="form">

    </textarea>
    <br/>
    <input type="date" name="day" form="form">
    <input type="submit" id="create" value="Submit" form="form">
</body>
</html>

【问题讨论】:

  • $(this) 在这种情况下 not 是否指的是表单,您为什么期望这样?你可以自己解决,绝对。开始使用您的浏览器开发控制台并输出$(this)。查看对象...
  • 对,我将使用控制台。谢谢,

标签: jquery html


【解决方案1】:

我相信这应该可以解决问题:

  1. 使用 jQuery 循环输入您的输入以提取您的值。
  2. 将值存储在新对象中。
  3. 将此对象传递给您的 Ajax 调用。

你只需要添加这段代码(来源:Obtain form input fields using jQuery?

var values = {};

$.each($('#myForm input').serializeArray(), function(i, field) {
values[field.name] = field.value;
});

并将values 作为数据传递给您的Ajax 调用。

这是 JSFiddle 中的示例:https://jsfiddle.net/gsdfoyu5/6/

【讨论】:

  • 这很好,但不适用于 textarea(仅迭代输入)。我使用了这段代码:date: document.getElementById("day").value, note: document.getElementById("note").value 作为请求数据中的对象。
猜你喜欢
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2010-09-26
  • 2021-12-10
相关资源
最近更新 更多