2013-07-14 369 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