gpt4 book ai didi

javascript - 如何让 jQuery AJAX 将 .map 函数 var 值作为 JSON 字符串发布

转载 作者:行者123 更新时间:2023-12-03 06:38:15 25 4
gpt4 key购买 nike

在下面选项 A 的示例中,当回显发布数据时,PHP 脚本发布结果显示 undefined。但同时 console.log 显示:[Object { set_capture="resize", set_unknown="unknown"}]。我想知道选项 A 中的 .map 函数或 ajax 代码有什么问题?对于选项 B,删除 .map 函数后效果很好。我缺少什么?

HTML 表单:

<form action="myphp.php" method="post" name="form-foo">
<input type="radio" id="r1" class="set-img" name="set_capture" value="resize" />
<input type="radio" id="r2" class="set-img" name="set_capture" value="original" />
<input type="checkbox" id="r3" class="set-img" name="set_unknown" value="unknown" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>

选项A:

$(function() {
$("#submit").on("click", function() {
var radioValues = $('#form-foo').map(function() {
return {
set_capture: $('input[name="set_capture"]:checked').val(),
set_unknown: $('input[name="set_unknown"]:checked').val()
};
}).get();
console.log(radioValues);
//var formData = JSON.stringify(radioValues);
var formData = radioValues;
var formURL = $("#form-foo").attr("action");
console.log(formData);
$.ajax({
url: formURL,
type: "POST",
data: formData,
cache: false,
dataType: "json"
}).done(function(data) {
// more codes
}, "json");
return false;
});
});

选项B:

$(function() {
$("#submit").on("click", function() {
var capture = $('input[name="set_capture"]:checked').val();
var unknown = $('input[name="set_unknown"]:checked').val();
var formData = {
set_capture: capture,
set_unknown: unknown
};
var formURL = $("#form-foo").attr("action");
console.log(formData);
$.ajax({
url: formURL,
type: "POST",
data: formData,
cache: false,
dataType: "json"
}).done(function(data) {
// more codes
}, "json");
return false;
});
});

最佳答案

.map 始终以数组形式返回。Ajax 数据格式是对象 {} 因此,它将在您的 POST 中未定义。要解决这个问题,您需要添加 formdata

的索引 0
$.ajax({
url: formURL,
type: "POST",
data: formData[0], //here add index 0
cache: false,
dataType: "json"
}).done(function(data) {
// more codes
}, "json");
return false;
});

Note : data is never pass undefined value to server post ,so if you didn't check your input or checkbox,It will post nothing...

关于javascript - 如何让 jQuery AJAX 将 .map 函数 var 值作为 JSON 字符串发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089994/

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