我正在构建一个表单,允许用户向网站提交信息以供发布。我在可编辑HTML标记上使用contenteditable=true
的内联编辑组合,还使用标准表单输入,如选择和文本字段。
当用户提交表单时,我希望它通过Ajax实现。我知道如何序列化表单本身,但我不知道如何同时序列化设置了contenteditable=true
的HTML元素,以便将其全部打包发送到服务器。
下面是一些HTML代码示例:
<form action="/path/to/server/file" enctype="multipart/form-data">
<!--- Start WYSIWYG Inline Editing --->
<div id="ItemContainer">
<h1 id="ItemTitle" contenteditable="true">A title would go here</h1>
<h2 id="ItemSubtitle" contenteditable="true">A subtitle here</h2>
<div id="ItemMainBody" contenteditable="true">
<p>Integer condimentum sit amet, tempor elit odio, a dolor non ante at sapien. Sed ac lectus. Nulla ligula quis eleifend mi, id leo velit pede cursus arcu id nulla ac lectus. Phasellus vestibulum. Nunc viverra enim quis diam.</p>
<p>Donec ullamcorper, risus tortor, pretium porttitor. Morbi quam quis lectus non leo.</p>
<img src="/path/to/imagefile" />
</div>
</div>
<!--- End WYSIWYG Inline Editing. Standard Form elements follow... --->
<select name="ItemCategory" id="ItemCategory">
<option value="1">Planes</option>
<option value="2">Trains</option>
<option value="3">Automobiles</option>
</select>
<input type="text" name="ItemURL" id="ItemURL">
<input type="submit" name="Submit" id="Submit" value="Submit"/>
</form>
要通过ajax提交,我目前会这样做:
('form').submit(function (e) {
$.ajax({
type: 'post',
url: '/path/to/formprocessor',
data: $('form').serializeArray(), // serializing the form
dataType: "json",
done: function (result) {
// tell user its done!
},
error: function (result) {
alert("An error has occured.");
}
});
e.preventDefault();
});
如何序列化HTML元素,以便将所有内容一起提交?我想要contenteditable元素的ID来表示它的名称。所以在POST中我希望看到:
ItemCategory 1
ItemTitle A title would go here
ItemSubtitle A subtitle here
ItemURL http://www.com
ItemMainBody <p>Integer condimentum sit amet, tempor elit odio, a dolor non ante at sapien. Sed ac lectus. Nulla ligula quis eleifend mi, id leo velit pede cursus arcu id nulla ac lectus. Phasellus vestibulum. Nunc viverra enim quis diam.</p>
<p>Donec ullamcorper, risus tortor, pretium porttitor. Morbi quam quis lectus non leo.</p>
<img src="/path/to/imagefile" />
在这种情况下,您必须在提交之前手动将参数添加到数组中,下面是JS代码:
('form').submit(function(e) {
var formToSubmit = e.target;
var serialisedFormArrayObject = $(formToSubmit).serializeArray();
var $contentEditableItems = $("[contenteditable=true]");
$contentEditableItems.each(function(index) {
serialisedFormArrayObject.push({
name: $contentEditableItems[index].id,
value: $contentEditableItems[index].innerHTML
});
});
$.ajax({
type: 'post',
url: '/path/to/formprocessor',
data: serialisedFormArrayObject,
dataType: "json",
done: function(result) {
// tell user its done!
},
error: function(result) {
alert("An error has occured.");
}
});
e.preventDefault();
});
- 经过编辑以在澄清后回答实际问题,尽管以下信息可能对其他人仍然有用
为了转义html字符串,您需要使用内置的Javascript方法encodeURIComponent。例如,如果你有:
console.log(encodeURIComponent("<div>potato</div>"));
您将获得:%3div%3Potato%3C%2div%3E根据您在服务器端使用的语言,然后可以对其进行解码。
请注意允许用户输入script
标签,因为这可能导致跨站点脚本(XSS)攻击
所以你需要改变的线路
data:$(this).serializeArray(),//序列化表单
至
data: encodeURIComponent($(this).serializeArray()), // serializing the form
最后,如果您希望表单作为查询字符串而不是表单内容提交,则需要将谓词设置为GET,而不是POST
尝试
$("form").click(function (e) {
e.preventDefault();
$("#ItemURL").val(location.href);
var res = $(this).serializeArray(); // serializing the form
// `serialize` `ItemContainer` elements to `{name:value}` pairs
$("#ItemContainer *[id^=Item]")
.each(function(i, el) {
var j = {};
j.name = el.id;
j.value = $.trim(el.innerHTML);
res.push(j)
});
$.ajax({
type: "POST",
url: "/echo/json/",
data: {json:JSON.stringify(res)},
dataType: "json",
// substitute `success` for `done` _within_ `ajaxSettings` ,
// utilize `.done` or `.then` _after_ ,
// i.e.g., `$.ajax({}).done()` , `$.ajax({}).then()`
success: function (result) {
// tell user its done!
$("pre").text(JSON.stringify(result, null, 4))
},
error: function (result) {
alert("An error has occured.");
}
});
});
jsfiddlehttp://jsfiddle.net/guest271314/3zn4Lbab/