我正在努力使用 PHP 调用 JS 函数 firstLetterSearch()
,并将变量 $_POST['word']
传递给它。
我可以发送一个 int 作为参数,但如果我发送此变量,那么当我将值记录到控制台时,它只会显示为 {}
。
function firstLetterSearch(firstLetter){
console.log('First letter search function called');
let abc = JSON.stringify(firstLetter);
console.log(abc);
if(firstLetter === 1){
console.log('I will select word starting with A');
} else if(firstLetter === 2){
console.log('I will select word starting with B');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
<script language="javascript" src="words.js" type="text/javascript"></script>
</head>
<body onload="updateChat();">
<p id=shownword></p>
<form action="" method="post">
<input type="submit" name="word"
class="button" value="a" id="a"/>
<input type="submit" name="word"
class="button" value="b" id="b"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
echo '<script type="text/javascript">',
'firstLetterSearch(';
echo $_POST['word'];
echo ');',
'</script>';
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
//return;
}
?>
</body>
</html>
最佳答案
您的代码几乎可以运行。
说的部分
echo '<script type="text/javascript">',
'firstLetterSearch(';
echo $_POST['word'];
echo ');',
'</script>';
当你真正想要 firstLetterSearch("a");
firstLetterSearch(a);
所以只需将其更改为:
echo '<script type="text/javascript">',
'firstLetterSearch("';
echo $_POST['word'];
echo '");',
'</script>';
关于javascript - PHP 不向 JS 发送变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681085/