出于多种原因(首要原因为学习JavaScript),我需要在没有jQuery的情况下将表单序列化,并使用ajax将生成的序列化数据结构发送到php页面。 序列化的数据必须是JSON格式。
我该如何做呢?
--编辑--
这是我的表单样式:http://jsfiddle.net/XGD4X/
出于多种原因(首要原因为学习JavaScript),我需要在没有jQuery的情况下将表单序列化,并使用ajax将生成的序列化数据结构发送到php页面。 序列化的数据必须是JSON格式。
我该如何做呢?
--编辑--
这是我的表单样式:http://jsfiddle.net/XGD4X/
我正在解决类似的问题,我认为在使用框架之前学习如何编程是值得的。我使用一个数据对象(BP.reading)来保存信息,例如血压读数。然后使用JSON.stringify(dataObj)即可完成工作。
这里是“保存”按钮单击的处理程序,它是数据对象上的一个方法。请注意,我使用表单而不是表格来输入数据,但是相同的思路应该适用。
update: function () {
var arr = document.getElementById("BP_input_form").firstChild.elements,
request = JDK.makeAjaxPost(); // simple cross-browser httpxmlrequest with post headings preset
// gather the data and store in this data obj
this.name = arr[0].value.trim();
...
this.systolic = arr[3].value;
this.diastolic = arr[4].value;
// still testing so just put server message on page
request.callback = function (text) {
msgDiv.innerHTML += 'server said ' + text;
};
//
request.call("BP_update_server.php", JSON.stringify(this));
}
我在我的程序中使用对象来发送、接收、显示和输入相同类型的数据,因此我已经准备好了对象。如果您想要更快速的解决方案,可以使用一个空对象并向其中添加数据。如果数据是一组相同类型的数据,则只需使用数组即可。然而,使用对象在服务器端具有有用的名称。以下是一个更通用的版本,尽管未经测试,但已通过jslint。
function postUsingJSON() {
// collect elements that hold data on the page, here I have an array
var elms = document.getElementById('parent_id').elements,
// create a post request object
// JDK is a namespace I use for helper function I intend to use in other
// programs or that i use over and over
// makeAjaxPost returns a request object with post header prefilled
req = JDK.makeAjaxPost(),
// create object to hold the data, or use one you have already
dataObj = {}, // empty object or use array dataArray = []
n = elms.length - 1; // last field in form
// next add the data to the object, trim whitespace
// use meaningful names here to make it easy on the server side
dataObj.dataFromField0 = elms[0].value.trim(); // dataArray[0] =
// ....
dataObj.dataFromFieldn = elms[n].value;
// define a callback method on post to use the server response
req.callback = function (text) {
// ...
};
// JDK.makeAjaxPost.call(ULR, data)
req.call('handle_post_on_server.php', JSON.stringify(dataObj));
}
祝你好运。
serialize = (form) ->
enabled = [].filter.call form.elements, (node) -> not node.disabled
pairs = [].map.call enabled, (node) ->
encoded = [node.name, node.value].map(encodeURIComponent)
encoded.join '='
pairs.join '&'
serialize = (form) ->
data = {}
for node in form.elements when not node.disabled and node.name
data[node.name] = node.value
data
我没有查看jQuery的实现,因此无法保证100%的兼容性。