作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在下面选项 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
$.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/
我是一名优秀的程序员,十分优秀!