来自javascript的字符串“true”在php中未被识别为该字符串值

我在 php 函数中调用一个 javascript 查询来测试用户是否想要允许某些操作。返回的值javascript是字符串值 'true' 或 'false'。如果我测试php以查看字符串是否返回 true,如果我测试为 $var=='true' 则返回 false。请帮助我显然愚蠢的疏忽。


我已经测试过它以确保它有多种方法可以查看返回的值,字符串,布尔值,1,0 整数,但表示字符串


    if (file_exists($target_file)) {

    function prompt($prompt_msg){

    echo("<script type='text/javascript'> var answer = confirm('".$prompt_msg."'); </script>");


    $answer = "<script type='text/javascript'> document.write(answer); </script>";

    return($answer);

    }

    //program


    $prompt_msg = "Overwrite curent file?";

    $name = prompt($prompt_msg);


    }


    //This returns 'true' or  'false' string value for php sake


    if (is_string($name))

    {echo "YES";} else 

    {echo "NO";}


    //This always returns YES if I select OK (true) or Cancel (false) in above javascript


    echo gettype($name);


    //This returns string


    echo $name;


    /*****/   if($name == 'true') {

    $uo = 1;

    echo 'success';

    } elseif($name == 'false') {

    $uo = 0;

    }

    else {;

    $uo = '??';

    }

    echo $uo;

***//如果我用 if($name == true) 替换这个语句,无论 javascript 返回的字符串是 true 还是 false,它总是给出 $uo = 1;


//javascript 的值是 'true' 还是 'false' 总是会返回 ??


Php if 查询应该分配 1 给 $uo if 'true' else '0' if false


万千封印
浏览 195回答 3
3回答

绝地无双

PHP 是服务器端,JavaScript 是客户端(不考虑 NodeJS)。也就是说,当你调用页面时,PHP 完全运行,无需等待你制作的 JavaScript,实际上 PHP 只构建包含脚本的网页,只有当浏览器收到该页面时才会执行 JavaScript,但 PHP 已经完成它的所有执行。在您的示例代码中,$answer包含的是字符串<script type='text/javascript'> document.write(answer); </script>而不是 JavaScript 的执行结果,因为 PHP 无法执行这样的脚本。如果要在浏览器上下文中执行此 PHP,则需要更改 JavaScript 以调用在查询中传递确认对话框值的 PHP url,并且 PHP 使用类似的内容检查传递的查询,parse_str($_SERVER['QUERY_STRING'], $query);并且仅在以下情况下构建页面none 被传递并继续执行,如果它收到true.@v-prince 的回答让你知道如何做客户端。

牛魔王的故事

我希望这会给你一些想法..祝你好运示例.html<input type='button' class='test'><!-- make sure you have a jquery plugin and check the path of your jquery --><script src="jquery.js"></script><script>$(document).ready(function(){&nbsp; $('.test').click(function(){&nbsp; &nbsp;var answer = confirm('are you sure you want to click me?');&nbsp; &nbsp;$.ajax({&nbsp; &nbsp; url : 'yourPHP.php',&nbsp; &nbsp; type : 'post',&nbsp; &nbsp; data : { answerValue : answer },&nbsp; &nbsp; success : function( result ){&nbsp; &nbsp; &nbsp;// do something&nbsp; &nbsp; }&nbsp; });&nbsp;});});</script>

小唯快跑啊

您的条件将在 PHP 中执行,而不是在 javascript 中执行。转换为布尔值时,以下值被视为 FALSE:the boolean FALSE itselfthe integer 0 (zero)the float 0.0 (zero)the empty string, and the string "0"an array with zero elementsan object with zero member variables (PHP 4 only)the special type NULL (including unset variables)SimpleXML objects created from empty tags还要注意var_dump(0==FALSE);&nbsp; &nbsp; //bool(true)&nbsp;&nbsp;var_dump(0===FALSE);&nbsp; &nbsp;//bool(false)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript