通过 jQuery 进行数据处理后替换 iframe 的内容
我有以下函数用于从服务器获取 HTML 模板并替换一些标签
$.ajax({
url: "/newsletter/preview/1",
data: {},
success: function(data) {
var template = data;
var layer = $("<iframe>").attr({ "id": "preview_frame" });
$("#newsletter .element input, #newsletter .element textarea").each(function() {
var id = "\\$\\$"+$(this).parent().parent().attr("id").replace(/^newsletter_/, "")+"\\$\\$";
template = template.replace(new RegExp(id, "g"), htmlspecialchars($(this).val(),2));
});
$("body").prepend(layer);
},
dataType: "html"
});
获取模板工作正常。还将标签替换为表单内容(当将 alert(escape(template));
放入 each
循环中时,我会看到所有标签都被替换)。但还有两个未解决的问题:
我没有找到将变量
template
的内容设置到 iframe 中的方法 ($("#preview_frame").contents().find("body").html(template);
结果仅在空框架中)将 iframe(变量
layer
)添加到 HTML 主体中 在遍历表单字段期间,但必须在(!)之后完成 所有标签都已被替换,因此只有完整处理的模板才会被放置在 iframe 内。
I've following function for getting HTML template from server and replacing some tags
$.ajax({
url: "/newsletter/preview/1",
data: {},
success: function(data) {
var template = data;
var layer = $("<iframe>").attr({ "id": "preview_frame" });
$("#newsletter .element input, #newsletter .element textarea").each(function() {
var id = "\\$\\$"+$(this).parent().parent().attr("id").replace(/^newsletter_/, "")+"\\$\\$";
template = template.replace(new RegExp(id, "g"), htmlspecialchars($(this).val(),2));
});
$("body").prepend(layer);
},
dataType: "html"
});
Getting the template works fine. Also replacing the tags with content of form (when placing alert(escape(template));
inside each
loop shows me, that all tags are being replaced). But there are two unsolved problems yet:
I didn't find a way to set content of variable
template
into iframe
($("#preview_frame").contents().find("body").html(template);
results only in an empty frame)Prepending the iframe (variable
layer
) to the HTML body happens
during iterating through form fields, but it has to be done after(!)
all tags have been replaced, so that only the complete processed template is going to be placed inside the iframe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
动态添加一个 ifame,其来源是您的 ajax 调用 url,并在 iframe 页面的 onload 中执行 javascript 操作。
add an ifame dynamicly which source is your ajax call url, and do the javascript things in onload of your iframe page.
我现在正在使用 http://malsup.com/jquery/form/ 的 jQuery 表单插件。
因此,我通过 Ajax 将表单发送到服务器,服务器会生成临时文件,在成功发送表单后通过 iframe 包含该文件。
I'm using now form plugin for jQuery from http://malsup.com/jquery/form/.
So I'm sending form via Ajax to server, which generates temporary file that is included via iframe after successful sending form.