Warm tip: This article is reproduced from serverfault.com, please click

其他-在Javascript Jquery中调用PHP变量

(其他 - Call PHP variable inside Javascript Jquery)

发布于 2020-11-28 05:51:11

我的问题是当我尝试在js中使用php变量的值时。

此代码有效

var OmdbApi = 1fb4ed32;

但是,当我尝试使用与存储在变量中相同的值时,代码将中断

var OmdbApi = json_encode($mhflix_opc[\'omdb-api\']);

完整代码:

function custom_admin_js() {
    echo '
    <script>
    jQuery.noConflict();
    jQuery(\'input[name=Checkbx]\').click(function() {
    var coc = jQuery(\'input[name=Checkbx2]\').get(0).value;      
    var OmdbApi = json_encode($mhflix_opc[\'omdb-api\']);
    jQuery.getJSON("https://www.omdbapi.com/?apikey=" + OmdbApi + "&i=" + coc, function(data) {
        var valDir = "";
        var valWri = "";
        var valAct = "";
        var valCou = "";
        jQuery.each(data, function(key, val) {
              jQuery(\'input[name=\' +key+ \']\').val(val); 
              if(key == "Director"){
                valDir+= " "+val+",";
              }
              if(key == "Writer"){
                valWri+= " "+val+",";
              }
              if(key == "Actors"){
                valAct+= " "+val+",";
              }
              if(key == "Country"){
                valCou+= " "+val+",";
              }
        });
        jQuery(\'#new-tag-director\').val(valDir);
        jQuery(\'#new-tag-escritor\').val(valWri);
        jQuery(\'#new-tag-actor\').val(valAct);
        jQuery(\'#new-tag-country\').val(valCou);
        alert(\'Se generó todo automáticamente.\');
    }); 
});
</script>';
}
add_action('admin_footer', 'custom_admin_js');
Questioner
Marcelo Herrera
Viewed
0
farvilain 2020-11-28 16:50:03
function custom_admin_js() {
    //define the variable OmdbApi here, result must be a simple string
    $omdbApi = json_encode($mhflix_opc['omdb-api']);



    echo '<script>
    jQuery.noConflict();
    jQuery(\'input[name=Checkbx]\').click(function() {
    var coc = jQuery(\'input[name=Checkbx2]\').get(0).value;';


    //Here we want to produce, depending on the value
    // var OmdbApi = 'ekrpweg' ;
    echo 'var OmdbApi = "' . $omdbApi . '" ;';

    echo 'the rest of the echo here';
}