2013-08-18 56 views
0

我試圖計算通過AJAX文本框的值,計算事件onkeyup文本框的值:PHP:通過Ajax

的index.php

<html> 
<head> 
<script type="text/javascript"> 
function calc() { 
if (window.XMLHttpRequest) { 
    xmlhttp = new XMLHttpRequest(); 
    } else { 
    xmlhttp = new ActiveXObject('MicrosoftXMLHTTP'); 
    } 
    xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     document.getElementById('myDiv').innerHTML = xmlhttp.responseText; 
    } 
    } 
    var text = document.getElementById('txtField').value; 
    var target = "calc.php"; 
    var parameter = "txtValue=" + text; 

    xmlhttp.open('POST', target, true); 
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
    xmlhttp.send(parameter); 
} 
</script> 
</head> 
<body> 
Price: <input type="text" id="txtField" onkeyup="calc();"> 
<div id="myDiv"></div> 
</body> 
</html> 

calc.php

if ($_POST['txtValue'] && !empty($_POST['txtValue'])) { 
    echo $_POST['txtValue'] * 4; 
} 

但不會顯示結果。請告訴我我在這裏錯過了什麼?

回答

2

試圖改變自己的calc.php像:

if (isset($_POST['txtValue']) && !empty($_POST['txtValue'])) { 
    echo $_POST['txtValue'] * 4; 
} 
0

使用以下方法來看看你是否得到正確的響應:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     alert(xmlhttp.responseText); 
     document.getElementById('myDiv').innerHTML = xmlhttp.responseText; 
    } 



OK HRE是你的問題:
使用:

if (($_POST['txtValue'] != '') && !empty($_POST['txtValue'])) 


而不是:

if ($_POST['txtValue'] && !empty($_POST['txtValue'])) 


cuase $ _ POST [ 'txtValue']是不是一個布爾值,不能使用,如果條件

+0

沒有什麼變化。警告空值出 –

+0

所以現在回聲一些從calc.php簡單的東西 – Soosh

+0

我試過你的建議之前,但回聲空值 –