<form method="POST" action="/bm/upload-avatar/" enctype="multipart/form-data"
target="upload_iframe">
<iframe style="display: none" id="upload_iframe" name="upload_iframe"></iframe>
</form>
target="upload_iframe是为了和iframe建立关系
2.iframe伪ajax提交
<input id='bbb' type="submit">
3.绑定事件获取iframe返回值
<input id='bbb' type="submit" οnclick="iframe()">
function iframe() {
$('#upload_iframe').load(function () {
{# 获取iframe返回值#}
var iframeContents = this.contentWindow.document.body.innerText;
{# 如果是字典,就要JSON#}
{# iframeContents = JSON.parse(iframeContents);#}
});
}
4.获取的返回值为图片静态地址,将预览图片src地址换为该地址
function iframe() {
$('#upload_iframe').load(function () {
{# 获取iframe返回值#}
var iframeContents = this.contentWindow.document.body.innerText;
{# 如果是字典,就要JSON#}
{# iframeContents = JSON.parse(iframeContents);#}
if (iframeContents) {
$('#previewImg').attr('src', '/' + iframeContents);
}
});
}
5.干掉submit,实现更换后自动提交表单
$('#avatarImg').change(function () {
$(this).parent().submit();
$('#upload_iframe').load(function () {
{# 获取iframe返回值#}
var iframeContents = this.contentWindow.document.body.innerText;
{# 如果是字典,就要JSON#}
{# iframeContents = JSON.parse(iframeContents);#}
if (iframeContents) {
$('#previewImg').attr('src', '/' + iframeContents);
}
})
});
其中,JQ对象.change(),实现该功能 :
概述
当元素的值发生改变时,会发生 change 事件。