1

请有人让我知道如何在 JavaScript 中执行以下 PHP。PHP 中的变量是 Javascript 中的参数。如果设置了所有三个参数,那么我想要一个 PHP 脚本来执行:

<?php     
if isset($nation,$service,$slider)
    {
//execute php script
    }       
?>

感谢您的关注,也许会有所帮助!

为了消除任何混淆,我要求将上面的所有 PHP 转换为等效的 JavaScript。

最重要的是,如果设置了所有 3 个参数,我想要一种在 JavaScript 中执行 PHP 脚本的方法。

4

4 回答 4

3

Assuming none of your variables have a zero or null value, for example, if they're all strings, the shortest way to write variable checks is to just use them:

function blah (nation, service, slider)
{
    if (nation && service && slider)
    {
        // do something...
    }
}

If any of those vars have the value 0, false or null when set then this would not be the correct method. If you want the equivalent of the isset function, you could use this:

function isset()
{
    for (var i=0, l=arguments.length; i < l; i++)
    {
        if (typeof arguments[i] == "undefined" || typeof arguments[i] == "null")
            return false;
    }
    return true;
}

Use it the same as you would the php function, e.g. isset(nation,service,slider);

于 2010-02-06T10:22:54.260 回答
1

Check out the great phpjs.org stuff. It's a port of PHP functions into JavaScript.

The isset() function:

function isset () {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true

    var a=arguments, l=a.length, i=0;

    if (l===0) {
        throw new Error('Empty isset'); 
    }

    while (i!==l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}

Usage:

allVarsAvailable = isset(nation,service,slider);
于 2010-02-06T14:55:03.393 回答
0

From what I understand you are trying to do an AJAX call. If you were to use a framework like jQuery, the code would be something like:

if ((typeof nation != 'undefined') && (typeof service != 'undefined') && (typeof slider != 'undefined')) {
    $.get("<your script>", function(data){
         alert("Data Received: " + data);
    });
}

If this is not what you are looking for, please rephrase your question.

于 2010-02-06T10:10:24.190 回答
0

Haven't tested, but looks right:

function isset(variable_name){
  return(typeof(window[variable_name])!='undefined');
}

Note that variable_name is not a variable itself, but it's name.

于 2010-02-06T10:13:23.957 回答