将 php 变量分配给 javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18251164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:13:17  来源:igfitidea点击:

assign php variable to javascript variable

javascriptphpjquerymysqlajax

提问by Burak KO?AK

How can i assign value of a javascript variable using php variable

我如何使用 php 变量分配 javascript 变量的值

 $(function(){
    $("select[name=myselectlist]").change(function(){
        var id = $(this).val();
        if(id != 0) {       
            $.post("ajax.php", {"id":id}, function(){
                var data = "somedatahere";
                document.getElementById("namesurname").value = data;
            });
        }
    });
});

the code above works perfectly without php.Yet, i need to assign "var data" from mysql everytime.

上面的代码在没有 php 的情况下完美运行。但是,我每次都需要从 mysql 分配“var data”。

回答by Sahil Mittal

If your php var is in the scope of the file where you have this function, you can do it like this:

如果你的 php var 在你拥有这个函数的文件的范围内,你可以这样做:

var data = "<php echo $myvar; ?>";

回答by kryoz

1) You can do as Shadowfax wrote but more simple:

1)你可以像Shadowfax写的那样做,但更简单:

var data = '<?=$dbResult?>';

2) More correct. Pass your result to AJAX response with json_encodefunction in PHP so you can rewrite your JavaScript code block as follows:

2)更正确。使用json_encodePHP 中的函数将结果传递给 AJAX 响应,以便您可以按如下方式重写 JavaScript 代码块:

...
$.post("ajax.php", {"id":id}, function(response){
    $("#namesurname").val(response.data);
});

For example your PHP code block in backend may look like this:

例如,您后端的 PHP 代码块可能如下所示:

....
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')) {
    echo json_encode(array('data' => $dbResult));
}

回答by Dipendra Gurung

If this javascript code is in the php file, then you can simply use php variables as updated in the code:-

如果此 javascript 代码在 php 文件中,那么您可以简单地使用代码中更新的 php 变量:-

<?php
// assign a value
$data = 'your data here';
?>

$(function(){
    $("select[name=myselectlist]").change(function(){
        var id = $(this).val();
        if(id != 0) {       
            $.post("ajax.php", {"id":id}, function(){
                var data = "somedatahere";
                document.getElementById("namesurname").value = "<?php echo $data;?>";
            });
        }
    });
});