gpt4 book ai didi

javascript - JSON 表单数据作为动态提交

转载 作者:行者123 更新时间:2023-11-28 18:23:15 25 4
gpt4 key购买 nike

AJAX post 在传递预定义数据时起作用,如下所示:

//var data = {"name": "Testing", "email": "testing@gmail.com", "cpf": "9876543210"};

但是我无法从表单动态传递数据。

请帮我解决这个问题。

POST函数

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

$(function() {
$("#post").click(function() {
$("#dataIn").text(JSON.stringify($("form").serializeObject()));

$(function() {
//var data = {"name" : "Testing", "email" : "testing@gmail.com", "cpf" : "9876543210"};
var data = ("#dataIn");
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
//data: JSON.stringify(data),
contentType: "application/json",
});
});
});
});

表格

<form action="" method="post" class="form-inline">

<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">

<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">


<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">

<button id="post" type="submit" type="button">Add </button>
</form>

<p >Json Result</p>
<pre id="dataIn" ></pre>

我不确定是否必须序列化表单,或者 JSON.stringify(data) 是否已经可以做到这一点。

下面的代码完美运行:

非动态,但工作

    $("#post1").click(function(){
var data = {"name" : "Testing", "email" : "testing@gmail.com", "cpf" : "9876543210"};

$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: JSON.stringify(data),
contentType: "application/json",
});
console.log("Loaded");
});

谢谢。

最佳答案

目前我能想到的最佳解决方案:

$(function() {
$("#post").click(function() {
var data = JSON.stringify($("form").serializeObject());
$("#dataIn").text(data);
$(function() {
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: data,
contentType: "application/json",
});
});
});
});

您不需要使用 JSON.stringify() 两次,因为您已经对 .serializeObject() 返回值执行了此操作。接下来,将其打印到 #dataIn 容器并通过 ajax 请求发送。

关于javascript - JSON 表单数据作为动态提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39593596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com