正如標題所說,我想用 PHP 變數呼叫 javascript 函式,所以我使用 ajax 請求發送名為 [filename] 的變數來執行 javascript 函式,例如
上傳.php
<script>
function prepareforconvert(filenamse){
$.post('prepare.php', {filename: filenamse}, function(response){
alert('done');
});
}
</script>
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file))
{
$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
echo $target_file;
echo '<script>prepareforconvert("'.$target_file.'")</script>';
}
代碼應首先呼叫該函式,然后使用引數prepareforconvert發送一個發布請求prepare.php$target_file
準備.php
<script src='scripts\prepare.js'></script>
<?php
$UploadedImage = $_POST['filename'];
if (!empty($_POST["mail"])){
echo '<script>readFile("'.$UploadedImage.'")</script>';
}
?>
prepare.js 包含readFilejs函式
async function readFile(fileName) {
console.log({ fileName });
return await Tesseract.recognize(fileName, 'ara', {
logger: m => console.log(m)
});
}
async function parseDataFromTextAndPropertyNames(text, propertyNames) {
console.log({ text, propertyNames });
return propertyNames
.reduce((table, key) =>
Object.assign(table, {
[ key ]: RegExp(`${ key }\\W (\\w )`)
.exec(text)?.[1] ?? ''
}), {});
}
async function writeParsedTextDataAsJSON(fileName, table) {
console.log({ table });
JSON.stringify({ table });
// fake it ...
return (await new Promise(resolve =>
setTimeout(() => {
console.log({ fileName, json: JSON.stringify({ table }) });
resolve({ success: true });
}, 1500)
));
}
console.log('... running ...');
(async () => {
const { data: { text } } = await readFile('gfhgf.png');
const data = await
parseDataFromTextAndPropertyNames(text, ['???? ??????', '??? ??????']);
document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
const final = [JSON.stringify(data)];
console.log(data);
console.log(text);
const ff = [JSON.parse(final)];
console.log(final)
console.log(ff);
constructTable('#table',ff);
$("#table").excelexportjs({
containerid: "table",
datatype: 'table',
dataset: data,
columns: getColumns(data)
});
const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);
console.log({ result });
})();
如您所見,所有函式都是異步的,但我想組織此代碼僅在readFile從prepare.phppost 請求之后呼叫該函式時才起作用。我怎樣才能做到這一點,謝謝
uj5u.com熱心網友回復:
代替
echo '<script>prepareforconvert("'.$target_file.'")</script>';
然后是一個單獨的 AJAX 請求,這樣寫會更有意義
require "prepare.php";
而是在那個位置。
AJAX 請求似乎是多余的——您不需要額外往返服務器,因為 prepare.php 所需的所有資訊都已經存在于 upload.php 中......客戶端沒有添加任何新資訊——然后運行您的 AJAX 請求的輔助代碼。
也只需稍微修改 prepare.php 以便它不需要 POST 變數:
<script src='scripts\prepare.js'></script>
<?php
if (empty($target_file)){
echo '<script>readFile("'.$target_file.'")</script>';
}
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492848.html
標籤:javascript php jQuery 阿贾克斯
上一篇:修改ajax資料回傳
下一篇:會話過期后重定向到登錄頁面
