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>
    
    评论

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上