发布预览 – 使用AJAX和Fancybox传递数据
我正在尝试进行预览,这将出现在新的Fancybox iframe中。 几个星期以来,我正在寻求一些帮助或最佳实践,但我找不到它。
我的主要问题是将数据从表单(更新数据库之前)传递到Fancybox窗口。 我的AJAX技能很差,所以也许我的问题不是那么难。
请检查代码:
$('.preview2').fancybox({ fitToView : false, width : 905, height : 505, autoSize : false, closeClick : false, openEffect : 'none', closeEffect : 'none', ajax: { type: "POST", cache : false, url: "https://stackoverflow.com/questions/14316054/post-preview-passing-data-with-ajax-and-fancybox/preview.php", data: $('#postp').serialize() } });
和一个呼叫链接:
Preview
我几乎可以肯定使用https://stackoverflow.com/questions/14316054/post-preview-passing-data-with-ajax-and-fancybox/preview.php文件一切都很好,只需发布变量并将其打印在正确的位置即可。
有人可以检查Fancybox / AJAX部分吗?
正如我在评论中提到的,您的预览按钮应该通过ajax提交表单以获取POST预览值(我们将使用ajax
而不是iframe
),因此:
Preview
然后你需要将预览按钮绑定到手动on("click")
方法,首先通过ajax
提交表单….然后将结果发布在fancybox中,如下:
$(document).ready(function () { $('.preview2').on("click", function (e) { e.preventDefault(); // avoids calling https://stackoverflow.com/questions/14316054/post-preview-passing-data-with-ajax-and-fancybox/preview.php $.ajax({ type: "POST", cache: false, url: this.href, // https://stackoverflow.com/questions/14316054/post-preview-passing-data-with-ajax-and-fancybox/preview.php data: $("#postp").serializeArray(), // all form fields success: function (data) { // on success, post (preview) returned data in fancybox $.fancybox(data, { // fancybox API options fitToView: false, width: 905, height: 505, autoSize: false, closeClick: false, openEffect: 'none', closeEffect: 'none' }); // fancybox } // success }); // ajax }); // on }); // ready
查看DEMO (随意浏览源代码)
我不喜欢这个解决方案,所以我会发布自己的调查。
为什么用.on("click", ...
编写代码.on("click", ...
2. e.preventDefault
3. $.ajax
4. this.href
只是为了成功调用fancybox,那里面已经有了所有这些function ?
如果你决定使用ajax而不是iframe(比如在接受的答案中),你可以简单地将type
属性添加到fancybox()
调用,因为它已被检查,并通过所有其他
$('.preview2').fancybox({ type: "ajax", ajax: { data: $('#postp').serialize() // url: "someurl.php" not needed here, it's taken from href // if you need it, eg you have a button, not a link // use "href" property that overrides everything // not attribute, cause it's invalid } // href: "url_to_add_or_override_existing_one", // all other effects // afterLoad: function () { // other cool stuff } });
编辑由于@JFK指出它是不够的,每次单击链接时都必须获取表单数据,因此需要beforeLoad()
而不是data
。 Finnaly:
$('.preview2').fancybox({ type: "ajax", beforeLoad: function() { this.ajax.data = $('#postp').serialize(); } });
您也可以删除所有data-*
atrributes
小提琴
吻
我用fancybox尝试了一种更有趣的方式,
在fancybox页面中
var myvar; $(document).ready(function(){ myvar = parent.$("#formvariwant").val(); });