2017-06-14 45 views
0

我正在研究計算費用的ajax代碼。
它工作正常,但如果我輸入第二個操作它停止。首次計算後Ajax代碼停止

<script> 
var weight = document.getElementById("weight").value; 
var ship_type = document.getElementById("ship_type").value; 
var eol = document.getElementById("eol").value; 
function showFees(e) { 
    e.preventDefault(); 
    if (weight === 0) { 
    document.getElementById("txtHint").innerHTML = "no thing"; 
    return; 
    } else { 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    document.getElementById("txtHint").innerHTML = this.responseText; 
    } 
    }; 
    xmlhttp.open("GET", "sdr.php?weight=" + weight + "&ship_type=" + ship_type + "&eol=" + eol, true); 
    xmlhttp.send(); 
    } 
} 
</script> 

回答

1

那是因爲你得到的輸入值的功能之外,它加載值第一時間和相同的數據獲取一次又一次當showFees函數被調用。嘗試下面的代碼來解決這個問題,

var objWeight = document.getElementById("weight"); 
var objShip_type = document.getElementById("ship_type"); 
var objEol = document.getElementById("eol"); 
function showFees(e) { 
    var weight = objWeight.value; 
    var ship_type = objShip_type.value; 
    var eol = objEol.value; 
    e.preventDefault(); 
    if (weight === 0) { 
    document.getElementById("txtHint").innerHTML = "no thing"; 
    return; 
    } else { 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    document.getElementById("txtHint").innerHTML = this.responseText; 
    } 
    }; 
    xmlhttp.open("GET", "sdr.php?weight=" + weight + "&ship_type=" + ship_type + "&eol=" + eol, true); 
    xmlhttp.send(); 
    } 
} 
+1

那工作,謝謝你 – user3721008

+0

歡迎。將來你應該清除你的問題,就像你多次調用'showFees'一樣,並且響應沒有變化。這樣SO用戶就可以毫無困惑地回答它。 –