2013-07-14 284 views
1

我ajax_form.php頁:顯示在同一頁面Ajax內容沒有頁面加載

<html><head> 
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
<meta content="utf-8" http-equiv="encoding"> 
<script> 
function showUser(form, e) { 
e.preventDefault(); 
var xmlhttp; 
var submit = form.getElementsByClassName('submit')[0]; 
var sent = document.getElementsByName('sent')[0].value || ''; 
var id = document.getElementsByName('id')[0].value || ''; 


if (sent==""){ 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
} 

if (window.XMLHttpRequest) { 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
} else { 
    // code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 

xmlhttp.onreadystatechange=function(e) { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
} 
xmlhttp.open(form.method, form.action, true); 
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value); 
} 
</script> 

<form action="ajax_test.php" method="POST"> 
Enter the sentence: <input type="text" name="sent"><br> 
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)"> 
</form> 

<br>UPDATE <br> 

<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)"> 
<pre> 
    Enter the ID : <input type="text" name="id"><br> 
    Enter the sentence: <input type="text" name="sent"><br> 
</pre> 
<input type="submit" class="submit" value="submit" name="update" > 
</form> <br> 
<div id="txtHint"> 
<b>Person info will be listed here.</b> 
</div> 
</body> 
</html> 

和ajax_test.php是:

<html><head> 
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
<meta content="utf-8" http-equiv="encoding"> 
</head> <body > 
<?php 
// $q = $_POST["q"]; 
// you never process the $q var so i commented it 
if (isset($_POST['insert']) && $_POST['insert'] !== '') { 
echo "Operation: Insert","<br>"; 

$s = $_POST['sent']; 

$flag = 0; 

echo "Entered sentence : $s"; 

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"), 
    $matches)){ //Values stored in ma. 
    $x = (int) $matches[1][0]; //optionally cast to int 
    $y = (int) $matches[1][1]; 
} 

echo "<br>", 
    "Positive count :$x", 
    "<br>", 
    "Negative count :$y", 
    "<br>"; 

//---------------DB stuff -------------------- 
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test'); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$sql1 = "INSERT INTO table2 
     (id,sent,pcount,ncount,flag) 
     VALUES 
     ('','".$_POST['sent']."',' $x ','$y','$flag')"; 
if (mysqli_query($con, $sql1)) { 
    echo "1 record added"; 
} else { 
    die('Error: ' . mysqli_error($con)); 
} 


mysqli_close($con); 
} 

// -------------------------------UPDATE -------------------------- 
if (isset($_POST['update']) && $_POST['update'] !== '') { 
echo "Operation: update", "<br>"; 
// you say update but you are actually inserting below 

$s = $_POST['sent']; 
$flag = 1; 

echo "Entered sentence : $s"; 

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"), 
    $matches)) //Values stored in ma. 
{ 
    $x = (int) $matches[1][0]; //optionally cast to int 
    $y = (int) $matches[1][1]; 
} 

echo "<br>", 
    "Positive count :$x", 
    "<br>", 
    "Negative count :$y", 
    "<br>"; 

//---------------DB stuff -------------------- 
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test'); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$sql1 = "INSERT INTO table2 
     (id,sent,pcount,ncount,flag) 
     VALUES 
     ('','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes 
if (mysqli_query($con, $sql1)) { 
    echo "1 record added"; 
} else { 
    die('Error: ' . mysqli_error($con)); 
} 

mysqli_close($con); 
} 
?></html > </body > 

在Form1我已經把函數調用按鈕單擊事件,它工作正常。但在按鈕上單擊它加載頁面並重定向到ajax_test.php。我們可以說它正確使用ajax嗎?

在第二種形式中,我保留了函數調用的形式本身,並按照腳本中的要求進行了編碼。但按鈕上點擊行動發生。函數調用或其他錯誤是錯誤的嗎?

如何在兩種情況下顯示沒有頁面加載(刷新)的結果?

+0

@StevenMoseley:對不起,我簽了一段時間!我來檢查一下! – user123

+1

你不會偶爾使用IE嗎?在那裏你可能需要一個e.returnValue = false而不是e.preventDefault()。另一個使用像jQuery這樣的庫的原因隱藏了很多瀏覽器的不兼容性。它也會簡化你的代碼。 – mvw

+0

@mvw:謝謝,我希望'e.preventDefault(); e.returnValue = false;即使是IE也不會造成問題! – user123

回答

1

問題出在您的sent參數 - 它正在查找名爲「sent」的輸入,該輸入不存在。然後,如果未設置,則退出showUser功能。

這裏是有問題的片段(這下面我刪除):

if (sent==""){ 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
} 

除了這個問題,你還沒有接近</head>或打開<body>標籤,其本身是沒有問題的,但一個漂亮主要的格式問題。此外,請始終在您的<script>元素上放置一個type。最後,您應該關閉<meta /><input /><br />內聯元素。始終格式化你的代碼(每個heirarchical水平對自己的線條兄弟元素,4-空間標籤)可以幫助您找到小格式問題,如缺少的開身,等

這就是說,這個工作對我來說:

<html> 
<head> 
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> 
    <meta content="utf-8" http-equiv="encoding" /> 
    <script type="text/javascript"> 
    function showUser(form, e) { 
     e.preventDefault(); 
     var xmlhttp; 
     var submit = form.getElementsByClassName('submit')[0]; 
     var sent = document.getElementsByName('sent')[0].value || ''; 
     var id = document.getElementsByName('id')[0].value || ''; 

     if (window.XMLHttpRequest) { 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
     } else { 
      // code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.onreadystatechange = function(e) { 
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
       document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
      } 
     } 
     xmlhttp.open(form.method, form.action, true); 
     xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value); 
    } 
    </script> 
</head> 
<body> 
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)"> 
     <label>Enter the sentence: <input type="text" name="sent"></label><br /> 
     <input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)" /> 
    </form> 

    <h4>UPDATE</h4> 
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)"> 
     <pre> 
      <label>Enter the ID:</label> 
      <input type="text" name="id"><br> 
      <label>Enter the sentence:</label> 
      <input type="text" name="sent"><br> 
     </pre> 
     <input type="submit" class="submit" value="submit" name="update" /> 
    </form> 

    <br /> 
    <div id="txtHint"> 
     <b>Person info will be listed here.</b> 
    </div> 
</body> 
</html> 
+0

感謝哥們,我學會了至少如何編碼。 但我的問題仍然存在。一旦我點擊按鈕,它什麼都不顯示。 – user123

+1

嘗試使用Firebug for Firefox等調試器。它可以幫助您瞭解正在發生的事情,有效的工作以及出現問題的地方。在Ajax響應處理程序中設置一個斷點,以檢查您是否通過Ajax調用獲得了期望。在innerHTML周圍使用斷點來查看是否用期望更新了DOM。 – mvw

+0

網絡選項卡允許您檢查Ajax請求和響應。 – mvw