无法使用jquery.post更改变量

时间:2018-03-24 19:16:58

标签: javascript jquery

如果数据输出为true但我无法将var code值更改为"asd"

当前结果

enter image description here

jquery代码

$('.generate').click(function() {
      var code = "vhe8t";

      $.post('functions/functions.php', {
        fun: "code_generate",
        string: code
      }, function(data) {
        if (data == "true") {
          code = "asd";
          console.log("hello world");
        }
      })

     console.log(code);
});

功能.php代码

<?php

  $connection = new mysqli("localhost", "root", "root", "shop_management");

  $fun = "";
  if (isset($_POST['fun'])) {
    $fun = $_POST['fun'];
  }

  if ($fun == "code_generate") {
    $code = $_POST['string'];
    $query = "SELECT * FROM code WHERE code='$code'";
    $run = mysqli_query($connection, $query);
    $nums = mysqli_num_rows($run);

    if ($nums > 0) {
      echo 'true';
    } else {
      echo 'false';
    }
  }
?>

1 个答案:

答案 0 :(得分:3)

$.post以异步方式运行。运行该功能时,它只会发出请求 - 响应尚未返回,因此当您运行console.log(code);时,{1}仍然没有在1毫秒内发生变化。

将其放入回调中:

code