gpt4 book ai didi

javascript - 我上传图像的 Javascript 和 PHP 通信有什么问题?

转载 作者:行者123 更新时间:2023-11-28 06:19:50 25 4
gpt4 key购买 nike

我被要求仅使用 Javascript (Ajax/Jquery/JSON)。为什么这不起作用?

这是我嵌入 HTML 脚本中的代码:

function uploadImage(){
$.post("signup/upload.php", function(data)
{
if(data['status']!='ok'){
$("#status").html(data['status']);
console.log("!Failure");
}else{
$('#status').html("Your picture was uploaded!");
console.log("Success");
}
});
}

$(document).ready(function () {
$('#uploadImageButton').on('click', function()
{
uploadImage();
});
});

这是 HTML:

<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Submit" id = "uploadImageButton" name="submit">

这是 PHP:

  $reply['status'] = 'ok';
<?php
if(isset($_POST['submit'])) {
if (isset($_FILES['upload'])) {
$allowed = array ('image/pjpeg', 'image/jpeg','image/JPG');
if (in_array($_FILES['upload']['type'], $allowed)) {
if (move_uploaded_file
($_FILES['upload']['tmp_name'], "/fakepath/www/upload_files/{$_FILES['upload']['name']}"))
{
$reply['status'] = 'ok';
echo '<p><em>The file has been uploaded!</em></p>';
}

} else {
echo '<p class="error">Please upload a JPEG or PNG image.</p>';
}
}
}
print json_encode($reply);
?>

最佳答案

您应该使用 $.ajax 请求,例如下面。

HTML:

<form enctype="multipart/form-data">
<input type="file" name="upload" id="fileToUpload">
<input type="submit" value="Submit" id = "uploadImageButton" name="submit">
<form>

JS:

$(function(){
$('body').on('submit', 'form', function(e){
e.preventDefault();

$.ajax({
type: "POST",
url: "signup/upload.php",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
//your code
}
});

return false;
})
})

希望这有帮助。

关于javascript - 我上传图像的 Javascript 和 PHP 通信有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com