2014-10-06 34 views
0

我想用jquery點擊一個按鈕上傳圖片。通過jquery上傳圖片後的方法

這裏是我的html ..

<input id="imgphno" type="text" maxlength="10" name="imgphno" /><br/><br/> 
<input id="file" type="file" name="file" /> 
<br/><br/> 
<input type="submit" name="submit" value="Send" id="sndimg"/> 

以及相關的jQuery ..

$(document).ready(function(){ 
$("#sndimg").click(function() { 
    imgphno = $("#imgphno").val(); 
    myimage = $("#file");//what should go here so that post will have image data from input=file 
    $.post("sendmsg.php", {imgphno: imgphno, imageData: myimage}, 
    function(data) { 
    alert(data); 
    }); 
} 
} 

在此先感謝!

+0

您可在此http://stackoverflow.com/questions/21164365/找到答案如何發送圖像到php文件使用ajax或http://stackoverflow.com/questions/19447435/ajax-upload-image和其他不同的[這裏](https:// www。 google.ch/search?q=site%3Astackoverflow.com+posting+an+image+with+ajax&oq=site%3Astackoverflow.com+posting+an+image+with+ajax) – Spokey 2014-10-06 08:35:00

+0

而不是使用'$(「#file 「)',爲什麼不去'$(」#file「)。val()'。前一個會給你''對象數組',後者給你'''路徑'''文件名'。 – 2014-10-06 08:36:22

回答

0

可以使用ajax將文件上傳到服務器,但要注意它並不是所有瀏覽器都支持(主要是IE瀏覽器有一些這方面的問題)。下面的代碼可用於使用ajax將整個表單發佈到服務器。這將允許支持它的瀏覽器上傳文件。

var formData = new FormData($('#ID_OF_YOUR_FORM')[0]);  
    $.ajax({ 
     url: "/urltophpscript.php", 
     type: "POST",   
     data: formData, 
     processData: false, 
     contentType: false,   
     dataType: "json", 
     success: function(data) { 
      if(data.success){ 
       // Do something 
      } 
      if(data.error){ 
       // DO something 
      } 
     }, 
     error: function() { 
      // Do something 
     } 
    }); 

但是,我寧願建議您使用所有瀏覽器都支持的解決方案。這是通過隱藏頁面上的iframe,其形式將被張貼到完成:上面

<form action="#" method="post" enctype="multipart/form-data" id="Inet" class="form-horizontal" name="Inet" > 
<iframe src="" id="ulframe" name="ulframe" style="display:none;"></iframe> 

的形式和iframe,其中內容將被張貼到。下面是用來將數據發送到iframe中,然後將代碼讀取PHP腳本回蕩爲JSON結果:

$('#Inet').attr('action', '/modules/module.intranett/ajax/intranett/createArticle.ajax.php'); 
$('#Inet').attr('target', 'ulframe'); 
$('#Inet').submit(); 

$('#ulframe').load(function(){ 
    var data = JSON.parse($('#ulframe').contents().text()); 
    if(data.success) { 
     // Do Something 
    } 
}); 
return false;