2016-11-24 79 views
0

这是我的HTML和JavaScript。使用javascript上传图片?

我正在尝试上传一个使用javascript的图像。

我没有找到一些使用jquery的例子,但希望下面的这个函数可以被修改来做同样的事情。

图像上传脚本是一个PHP脚本,它在表单正常发布时起作用,但在下面使用此函数时,它不会将图像发送到PHP脚本。 $ _FILES是空的。 如何修改此功能以发送图像?

<html><head> 
<script type="text/javascript"> 

function jax( ){ 

    pd = document.getElementById("pd").innerHTML; 
    i = document.getElementById("i").value; 

    url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i; 
    q="act=uploadPic&title=" + pd + "&i=" + i; 

    var ajaxRequest; 
    try{ 
     ajaxRequest = new XMLHttpRequest(); 
    } 
    catch (e){ 
     try{ 
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
     } 
     catch (e) { 
      try{ 
       ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
      catch (e){ 
       alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false; 
      } 
     } 
    } 
    ajaxRequest.onreadystatechange= function(){ 
     if(ajaxRequest.readyState == 4){ 
      r =ajaxRequest.responseText; 
      alert(r); 
     } 
    } 
    ajaxRequest.open("POST", url, true); 
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    ajaxRequest.send(q); 
}//func 

</script> 

</head> 
<body> 
    <form action="upload.php" method="post" enctype="multipart/form-data"> 
     <p> Title: <input type="text" name="pd" id="pd" value=" Title here " /> 
     <p> Image: <input type="file" name="i" id="i" /> 
     <p> <button onclick=" jax( ) "> Upload </button> 
    </form> 
</body> 
</html> 

的PHP脚本来验证,如果图像是派: ajax.php

<?php print_r($_FILES); ?> 

回答

0

这是我的功能,但不能比IE8工作下:

function jax(){ 
     url= "ajax.php?act=uploadPic"; 
     var formData = new FormData(document.forms[0]); 
     var xhr = new XMLHttpRequest(); 
     xhr.open('post',url,true); 
     xhr.onreadystatechange = function(){ 
      if (xhr.readyState == 4) { 
       if (xhr.status == 200) { 
        console.log(xhr.responseText); 
       } 
      } 
     } 

     xhr.addEventListener('progress',function(e){ 
      if (e.lengthComputable) { 
       console.log(e.loaded+'/'+e.total); 
      } 
     },false); 
     xhr.send(formData); 
} 
+0

我得到在IE8中的这个错误消息:'FormData'是未定义的&在Firefox中它只是通常提交表单,就像有一个提交按钮而不是ajax上传按钮 –