调用PHP Post Request中的js函数



在使用Jquery$.post()发出POST请求后,我试图调用一个javascript函数post请求发送base64图像数据并将其写入服务器。问题是post请求已经完成,文件已经上传,但没有调用javascript函数getCounterNumber();不工作,本应执行此的功能

function getCounterNumber(Path){
Tesseract.recognize(
Path,
'eng',
{ logger: m => console.log(m) }
).then(({ data: { text } }) => {
window.location.href = "getcounterreading.php?counterNumber="+text+"";
})
}

jQuerycrop button点击

var base64data = reader.result;
$.post('http://127.0.0.1/counter/uploadcounter.php', {image:base64data}, 
function(response){ 
bs_modal.modal('hide');
alert("success upload image");
window.location.href = "uploadcounter.php";
console.log(response);
});

uploadcounter.php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$folderPath = '../../uploads/counters/';
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
file_put_contents($file, $image_base64);
echo ("image uploaded successfully.");
console.log($file);
echo '<script>getCounterNumber("'.$file.'")</script>'; 
}

不要返回标记。返回一个JSON。

您的Javascript

(我使用$.ajax((而不是$.post((并没有什么特别的原因。也许是因为它更具描述性(:

let base64data = reader.result;
let postData = { image:base64data };
$.ajax({
type: "POST",
url: 'http://127.0.0.1/counter/uploadcounter.php',
data: postData,
success: (result) => {
bs_modal.modal('hide');
getCounterNumber(result.data.file);
alert("success upload image");
console.log(response);
},
error: (error) => {
alert("There was an error. Check JS Console.");
console.log(error);
},
dataType: 'json'
});

您的PHP

if ('POST' === $_SERVER['REQUEST_METHOD']) {
$folderPath = '../../uploads/counters/';

$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
file_put_contents($file, $image_base64);

header("Content-Type: application/json");
echo json_encode(["file" => $file]);
exit();
}

请注意,我还没有运行或测试代码。这只是一个你可以效仿的例子。

最新更新