"AjaxChat 창에"이미지 업로드 "기능을 추가하려고합니다. 서버로 업로드하는 것이 효과적이지만 업로드 된 파일의 tmp_name/위치를 반환 할 수 있어야합니다. 내 자바 스크립트에서 나는 다음과 같은 (주) 코드 (일부 설치 코드가 필요하기 때문에 생략되었습니다 - 업로드가 예상대로 작동)이 있습니다XMLHttpRequest에서 호출 된 PHP에서 Javascript로 값을 되 돌림
// 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 내에서 자바 스크립트 "경고"팝업을 생성 할 수 있음을 읽어
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
그러나 위의 라인은 아무것도하지 않는 것. 이것은 PHP를 직접 실행하지 않고 XMLHttpRequest를 사용하기 때문에 예상됩니까?
궁극적으로 내 목표는 이미지 URL을 만들고 img 태그에 넣고 ajaxChat.insertText를 사용하여 채팅 창으로 보낼 수 있도록 PHP를 호출 한 자바 스크립트로 업로드 된 파일의 이름을 다시 전달하는 것입니다.() 및 ajaxChat.sendMessage(). 비록 이것이 가능한지 PHP로 실행하고 있는지는 확실하지 않습니다. 어떻게하면이 일을 할 수 있습니까?
'echo'는 AJAX가 아닌 일반적인 양식 제출에만 적용됩니다. AJAX를 사용하면 스크립트의 출력은'xhr.responseText'에 있고'xhr.onload' 함수는 원하는대로 할 수 있습니다. – Barmar