在jQuery模板中检查参数是否在PHP中设置的最好方法是什么?


what is the best way to check if a parameter is set in PHP within a jQuery template?

什么是最好的方法来检查参数设置在jQuery模板内PHP ?

我有这样的代码:

var custID = '<?php echo htmlentities( $_GET['custID'] ); ?>';

我需要检查它是否设置,如果设置了,则回显该值,如果没有产生错误

我想说:

<?php
 if(isset($_GET['custID']))echo "var custID = '".$_GET['custID']."';";
 else echo "alert('error');";
?>

try this

var custID = <?php echo htmlentities( isset($_GET['custID']) ? $_GET['custID'] : "" ); ?>;

我要这样做,首先我们需要检查custID是否存在:

<?php
    $custId = isset($_GET['custID'] && !empty($_GET['custId']) ? htmlentities($_GET['custId']) : false;
    if(!$custId) {
        //cutsId don't exists, show your error
?>
    Error
    <script type="text/javascript">var custId = false;</script>
<?php } else { ?>
    <script type="text/javascript">var custId = '<?php echo $custId; ?>';</script>
<?php } ?>

可以确定javascript变量不会抛出错误。

脚本中还有另一种方式:

<script type="text/javascript">
var custId = '<?php echo isset($_GET['custId']) ? htmlentities($_GET['custId']) : false;?>';
</script>

请注意,我保留引号,否则它们可能是错误的,因为var custId = ;无效,但var custId = '';有效。

如果custId不存在,Javascript var将为空(不是未定义),您可以这样检查:

if(custId.length)
    //custId exists