各位大大好
小弟碰到一個問題
現在有一個表單
這個表單的最後要填上個人設定的密碼
而目前我是藉由ajax的方式來判斷他填的密碼是否正確
(不想送出才在後端才檢查,因為中間有很多要填的東西是透過ajax動態產生的
如果使用者打錯了 原本他填的會消失)
按下"送出"按鈕(id="submit")
只要他打的密碼是正確的
response的值會回傳空
不然就會跟他說錯誤
但當我這樣寫
submit卻無法在ajax success裡面生效
那一段確實有跑 也沒有報錯
請教各位大大
以下code:
$(document).on("click",'#submit',function(){
        var chk_code = $('#check_code').val();
        if(chk_code != "") {
            $.ajax({
                url: "../ajax.php",
                method: "POST",
                data: {
                    check_code: chk_code,
                },
                async: false,
                dataType: "text",
                success: function (response) {
                    if(response == '') {
                        $('#form1').submit();
                    } else {
                        alert(response);
                    }
                },
            })
        } else {
            alert('請輸入身分驗證碼');
        }
    })
response印出來看看$(document).on("click",'#submit',function(){
        var chk_code = $('#check_code').val();
        if(chk_code != "") {
            $.ajax({
                url: "../ajax.php",
                method: "POST",
                data: {
                    check_code: chk_code,
                },
                async: false,
                dataType: "text",
                success: function (response) {
                    if(response) {
                        $('#form1').submit();
                    } else {
                        alert(response);
                    }
                },
            })
        } else {
            alert('請輸入身分驗證碼');
        }
    })
3.如果可以,能否提供整份JS代碼
感謝大大的回覆
1.我有把response的印出來
確定ajax是可以正常運作的 回傳也抓的到
2.因為我後端直接用echo 的方式
所以用true會叫不回來哈哈
3.其實這就是全部的js了@@
一般的作法不會回傳空值,空字串在 JS 也是 false,很容易產生bug,例如下面的程式碼會判定為 false
const response = ''; 
if(response) {
  console.log('true')
} else {
  console.log('false')
}
~   
比較好的作法是回傳一個 json 來作判斷,例如
正確:
{"isSuccess": true, "msg": "code match"}
錯誤:
{"isSuccess": false, "msg": "code dismatch"}
原來如此
謝謝大大指教