简体   繁体   English

jQuery $ .post()使用输出数据作为选择器

[英]jQuery $.post() using output data as selector

I am trying to build a quiz environment. 我正在尝试建立测验环境。 The user selects an answer and then clicks submit. 用户选择一个答案,然后单击提交。 Upon submit, the following jquery is called: 提交后,将调用以下jquery:

$(document).ready(function() {
    $('.btn-large').click(function() {
        $.post("correct_quiz.php",
        {
            choices : $('input[name=choice][type=radio]:checked').serialize()
        },
        function(data) {
            var temp = '#correct' + data;
            var temp2 = '#correct3';
            $(temp).show();  // Make the wrong/right icons visible
        });
    });
});

This jquery makes a green or red icon appear, based on whether the answer was correct or not. 根据答案是否正确,该jquery会显示绿色或红色图标。 The correct_quiz.php script contains: correct_quiz.php脚本包含:

<?php 
       $root = "/users/stadius/maapc/public_html/";
       include($root . "connect_to_database.php");

       $choices = $_POST['choices']; // This will for example output "choice=3"
       echo substr($choices,7,7); // This will then output "3"
?>

I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. 我遇到了一个问题,当我尝试将上面的jQuery代码与temp2变量一起使用时,脚本可以像我想要的那样工作。 But when I try it with variable temp it doesn't. 但是,当我尝试使用可变温度时,它却没有。 When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer). 当我调试时,我看到它们包含完全相同的字符串:都是'#correct3'(当我选择第三个答案时)。

So why is this not working when I use variable temp, and is working when using temp2? 那么,为什么在使用可变temp时这不起作用,而在使用temp2时却起作用呢?

I think your problem is in this line: 我认为您的问题出在以下方面:

echo substr($choices,7,7);

Try to use: 尝试使用:

$list = explode('=', $choices);

echo $list[1];

instead of substr 代替substr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM