helloxielan 2014-09-30 12:18 采纳率: 0%
浏览 16

php到javascript并返回

I have a php file that generates some html and do some database queries. And there is some switch case statement. In one particular case I need to send to the user some dialog. If the user press OK I need to to some db queries and if the user press cancel I do not. So I decided to echo out a JavaScript code snippet which contains a confirm statement. So how can I send from the JavaScript the result of the confirm message back to php, and decide make a db query or not.

<?php 
// some code
switch $_REQUEST['action']
case 'save':
echo '<script type="text/javascript">',
     'if (!confirm("text + variables") ) { ajax=new XMLHttpRequest();
                                           ajax.open("POST",filename.php,true);
                                           ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                                           ajax.send("userChoice=false");
                                         }',
     '</script>';
if (!empty($_POST['userChoice'])) {
    echo 'got the variable from javascript!'
    // do some code
}

But unfortunately $_POST['userChoice'] is always empty. Does anybody know why?

  • 写回答

3条回答 默认 最新

  • weixin_33670713 2014-09-30 12:24
    关注

    You put in the filename without quotes.

    Javascript then doesn't know it is a string containing the filename, it thinks it's an object instance called filename with a property php.

    ajax.open("POST", "filename.php" ,true);
    

    Don't mix PHP and JS this way,... they are totally different languages, serverside, clientside,.

    Build your Javascript a way so it works without PHP.

    Let then PHP inject some configuration using:

    <script>
    var config = <?php json_encode($phpToJs); ?>;
    </script>
    
    评论
  • bug^君 2014-09-30 12:25
    关注

    Try to pass the parameter within the url when calling ajax.open();

    Example: filename.php?userChoice=false

    评论
  • 旧行李 2014-09-30 12:32
    关注

    You're missing break; and default in switch statment

    评论

报告相同问题?

悬赏问题

  • ¥15 存储过程或函数中的结果集类型变量如何使用。
  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信