[英]Receive JSON response from AJAX POST request?
我正在建立一个系统,供用户将个人资料图片上传到服务器。 这些个人资料图片使用 Croppie 裁剪,然后与 POST 请求一起发送到 PHP 文件进行处理。
如果图像被接受或出现错误,此 PHP 文件会从服务器接收响应。
我很难将此 JSON 响应传递回 AJAX 变量,因此我可以将其展示给最终用户。 我已经设置了一个 ID 为“json”的,应该在其中显示响应。 但是,显示的所有内容都是“未定义的”。
当显示没有.msg 的“响应”变量时,它会显示图像 URI - 因此它似乎没有接受 PHP 脚本中发出的请求。
这是我尝试过的:
AJAX
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
});
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">'
+ response.msg + '</div>');
})
});
PHP(脚本开始)
# Mechanism to upload image
if (isset($_POST['image'])) { # Check if image data is being sent by POST
$c_finalCheck = true;
$cropped_image = $_POST['image']; # Assign cropped_image from data received
$image_array_1 = explode(";", $cropped_image); # Create image with correct encoding
$image_array_2 = explode(",", $image_array_1[1]);
$cropped_image = base64_decode($image_array_2[1]);
$c_imgValid = getimagesize($c_fileCheck); # Set result of image validity and size check
if ($c_fileCheck == false) { # Run image validity check with response
$response['msg'] = 'Sorry, your image isn\'t valid. Please try again.';
$c_finalCheck = false;
header("Content-Type:application/json");
echo json_encode($response);
}
您正在将 Ajax 帖子发送到您的服务器,但您没有使用 Ajax 响应。 相反,您正在显示您的作物呼叫的响应。
你需要做这样的事情:
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
}).done(function(data) {
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">' + response + '</div>');
});
})
});
我没有尝试过,但它应该给你正确的方向。
这里 jquery Api 参考: Ajax
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.