繁体   English   中英

在 PHP 发布请求中调用 js function

[英]calling js function in PHP Post Request

I'm trying to call a javascript function after making a POST request using Jquery $.post() post request sends base64 image data and writes it down in the server the problem is that the post request is done and the file is uploaded but there没有 javascript function 调用getCounterNumber(); 不工作,function 应该这样做

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

jQuery crop 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);

              });

上传计数器.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();
}

请注意,我没有运行也没有测试过代码。 这只是一个示例,您可以将其作为灵感。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM