将ajax输出存储到变量中

时间:2015-09-19 01:20:00

标签: php jquery ajax variables

我必须检查天气发票编号是否重复,因为我正在使用以下ajax。

function check_duplicate_invoice(num){
          var isDuplicate ;

          xmlhttp = new XMLHttpRequest();
           xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
           xmlhttp.send();
           xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                    isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
                }
            }

            alert(isDuplicate); //result undefined

            if(isDuplicate== 1){
                alert("Invoice Number Already Exist");
            }
    }

我无法将ajax输出存储到isDuplicate变量中。请帮忙。

1 个答案:

答案 0 :(得分:1)

那是因为ajax调用是异步的。您在请求有时间完成之前查看变量。试试这个:

function check_duplicate_invoice(num){
      var isDuplicate ;

      xmlhttp = new XMLHttpRequest();
       xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
       xmlhttp.send();
       xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
                alert(isDuplicate); //result undefined

                if(isDuplicate== 1){
                   alert("Invoice Number Already Exist");
                }

            }
        }

}