[英]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.