ajax 图片上传

html 部分:

<form action="" id='myForm' enctype="multipart/form-data">
      <div style="0px; height:0px; overflow:hidden;">
           <input type='file' name='head' id='myHead' onchange="updateHead();"/>
      </div>
</form>

//触发控件
<img onclick="$('#myHead').click();" <if condition="empty($user['avatar'])">src="__IMG__/pic_04@2x.png"<else/>src="{$user.avatar}"</if> alt="" class='userphoto'/>

js部分: 

function updateHead(){
        var fd = new FormData(document.getElementById('myForm'));
        var xhr = new XMLHttpRequest();
        // xhr.open('post', 'user.php?act=update_head');
        xhr.open('post', "{:U('User/avatar_save')}");
        xhr.send(fd);
        xhr.onreadystatechange = function(){
            if ( xhr.readyState == 4 && xhr.status == 200 ) {
                var res = xhr.responseText;
                if(res=='1') location.reload();
            }
        };
    }
原文地址:https://www.cnblogs.com/wangyihong/p/7058986.html