[英]Ajax Post request to call javascript function
正如標題所說,我想用 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
,然后使用參數$target_file
向prepare.php
發送一個post請求
准備.php
<script src='scripts\prepare.js'></script>
<?php
$UploadedImage = $_POST['filename'];
if (!empty($_POST["mail"])){
echo '<script>readFile("'.$UploadedImage.'")</script>';
}
?>
prepare.js 包含readFile
js 函數
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 });
})();
如您所見,所有函數都是異步的,但我想組織此代碼僅在發布請求后從prepare.php
調用函數readFile
時才起作用。 我怎樣才能做到這一點,謝謝
代替
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>';
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.