javascript - PHP 不向 JS 发送变量

标签 javascript php

我正在努力使用 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/

相关文章:

PHP/MySQL - 创建每周报告

php - 当员工登录到特定模块时,我使用( session )变量来回显员工姓名

php - 让 MySQL 每个条目仅返回一行

php - 从 PHP 发送到 Ajax 的 json-data 地址

javascript - 将本地存储中的元素添加到 html 下拉菜单的建议

javascript - 无法从函数中调用removeEventListener

javascript - 错误 : Error parsing url: undefined when migrating database to heroku

javascript - 是否有 "onAnything"javascript 事件?

php - Cake PHP 3 导致过早注销

javascript - 如何在javascript中实现函数调用的任意链?