如何在javascript中对此查询使用AJAX调用? (选择*从问题所在的地方,问题数=问题数);

时间:2018-08-02 04:35:24

标签: javascript php ajax

这是我需要通过AJAX调用获得的搜索查询,

(SELECT * FROM questions WHERE questions_number = questions _number);

这是我将在其中使用的脚本

var m = new Map();


function randomize_questions(){

    while(m.size <= 20)
    {
        const x = parseInt(Math.random()*100);
        m.has(x) ? randomize_questions() : m.set(x,x); 
    }
    m.foreach( el => {
        const question_number = m.get(el);
     //Query->
    });

}

randomize_questions();

希望你们可以提供帮助:)

1 个答案:

答案 0 :(得分:0)

  1. 对于您的JS函数randomize_questions,为什么要使用递归?您最终可能会获得20层深的堆栈,并且在填充了地图之后,它将在20种元素中运行20次,以进行AJAX调用-在最坏的情况下,即对服务器进行400次AJAX调用场景。一个更简单的方法是:

    const random_number = () => {
      return parseInt(Math.random()*100);
    }
    const randomize_questions = async () => {
      var x;
      while(m.size <= 20) {
        x = random_number();
        while(m.has(x)) {
          x = random_number();
        }
        m.set(x,x);
      }
    };
    
    const get_questions = async () => {
      m.foreach(index => {
        // Perform AJAX call
        // You can fill this in :)
      });
    };
    
    await randomize_questions();
    await get_questions();
    
  2. 在服务器端,您会遇到类似这样的事情:

    <?php
    // Instantiate your DB connection, do validation that 
    // the request came from your page etc. Unfortunately
    // outside the scope of your question :)
    $question_id = $_GET['question_id'];
    
    // Going to assume you are using PDO with MySQL
    $stmt = $pdo->prepare('SELECT * FROM questions WHERE questions_number = ?');
    $stmt->execute([$question_id]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);
    // Return the data as needed, most probably as a JSON object
    echo json_encode($question);
    ?>