【发布时间】:2018-10-10 22:57:49
【问题描述】:
我正在处理带有表单的一页。
下面的 JS 脚本我需要帮助
当我按下提交时,我在 console.log 中获取数据,但我想要在服务器上的 json 文件或 xml 数据中,但每次我更改表单中的某些内容以在该文件中添加新数据时,而不是创建新数据文件
有什么帮助吗?
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function() {
var name = $(this).attr('name')
var type = $(this).attr('type')
if (name) {
var $value;
if (type == 'radio') {
$value = $('input[name=' + name + ']:checked', $form).val()
} else if (type == 'checkbox') {
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify($elements)
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="' + key + '"]', $form)
var type = $elem.first().attr('type')
if (type == 'radio') {
$('[name="' + key + '"][value="' + value + '"]').prop('checked', true)
} else if (type == 'checkbox' && (value == true || value == 'true')) {
$('[name="' + key + '"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}(jQuery));
$(document).ready(function() {
$("#_save").on('click', function() {
console.log("Saving form data...")
var data = $("form#test-form").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
});
【问题讨论】:
-
查看 AJAX/JSON - 你需要一个像 PHP 或类似的服务器进程
-
Javascript 是一种客户端语言——它不能直接与服务器通信。您需要对执行这些操作的服务器端脚本进行 Ajax 调用。
-
你的服务器端是什么?
标签: javascript jquery html json xml