2016-08-10 65 views
0

我試圖添加一個「上傳圖像」功能到我的AjaxChat窗口。上傳到服務器效果很好,但現在我需要能夠返回上傳文件的tmp_name /位置。在我的javascript我有如下(主)代碼(一些設置代碼已經因爲這是不必要的省略 - 上傳的作品如預期):從PHP返回值從PHP調用XMLHttpRequest

// Set up request 
var xhr = new XMLHttpRequest(); 

// Open connection 
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true); 

// Set up handler for when request finishes 
xhr.onload = function() { 
    if (xhr.status === 200) { 
     //File(s) uploaded 
     uploadButton.innerHTML = 'Upload'; 
    } else { 
     alert('An error occurred!'); 
    } 
}; 

// Send data 
xhr.send(formData); 

我的PHP代碼(「upload.php的」)是如下:

<?php 
$valid_file = true; 
echo '<script type="text/javascript">alert("PHP Code Reached");</script>'; 
if($_FILES['photo']['name']) { 
    //if no errors... 
    if(!$_FILES['photo']['error']) { 
     //now is the time to modify the future file name and validate the file 
     $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file 
     if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB 
      $valid_file = false; 
      $message = 'Oops! Your file\'s size is to large.'; 
      exit("$message"); 
     } 

     //if the file has passed the test 
     if($valid_file) { 
      //move it to where we want it to be 
      move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name); 
      $message = 'Congratulations! Your file was accepted.'; 
      exit("$message"); 
     } 
    } 
    //if there is an error... 
    else { 
     //set that to be the returned message 
     $message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error']; 
     exit("$message"); 
    } 
} 
?> 

我可以告訴我的PHP代碼正在運行,因爲圖像上傳到服務器。但是,我讀,我可以使用下面的代碼生成在PHP中一個JavaScript「警報」彈出:

echo '<script type="text/javascript">alert("PHP Code Reached");</script>';

但上面的線似乎並沒有被做任何事情。這是預期的,因爲我使用XMLHttpRequest,而不是直接運行PHP?

最終,我的目標是將上傳文件的名稱傳回給調用PHP的Javascript,以便我可以創建圖像url,將其放入img標記中,並使用ajaxChat.insertText將其發送到聊天窗口()和ajaxChat.sendMessage()。不過,我不確定這是否可以像我運行我的PHP一樣。如何去做這件事?

+0

'echo'只適用於正常的表單提交,而不是AJAX。使用AJAX,腳本的輸出位於'xhr.responseText'中,'xhr.onload'函數可以完成它所希望的功能。 – Barmar

回答

2

當您使用XMLHttpRequest時,服務器腳本的輸出位於對象的responseText中。所以,你可以這樣做:

xhr.onload = function() { 
    if (xhr.status === 200) { 
     //File(s) uploaded 
     uploadButton.innerHTML = xhr.responseText; 
    } else { 
     alert('An error occurred!'); 
    } 
}; 

如果你要發送回多條信息,如信息性消息和文件的名稱,你可以使用JSON編碼的關聯數組,這將成爲一個Javascript對象,當你解析它。

+0

所以我們假設我只想返回文件名(如果上傳成功),我可以在我的javascript中創建一個變量:'var returnedFileName = xhr.responseText;'並在我的PHP中刪除所有'exit(「$ message 「);'除了一個(在成功上傳的情況下):'$ message = $ new_file_name;退出(「$消息」);'這將工作來檢索使用JavaScript的PHP返回值?然後,我可以檢查返回的消息的格式,並確保它是一個有效的文件名(而不是錯誤消息或空)。我只是想確保我的理解正確。 – DerStrom8

+0

是的,你理解正確。所有腳本都會回覆到'xhr.responseText'中。 – Barmar

+0

剛剛測試過它,它的作品非常漂亮!非常感謝! – DerStrom8