簡體   English   中英

在沒有頁面加載的情況下在同一頁面中顯示ajax內容

[英]Showing ajax content in same page without page load

我的ajax_form.php頁面是:

<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嗎?

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

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

問題出在您的已sent參數上-它正在尋找不存在的名為“已發送”的輸入。 然后,如果未設置,則退出showUser函數。

這是令人討厭的代碼段(我在下面將其刪除):

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

除了該問題之外,您還沒有關閉</head>或打開的<body>標記,它們本身並不是問題,而是一個相當大的格式化問題。 另外,請始終在<script>元素上type 最后,您應該內聯關閉<meta /><input /><br />元素。 一致地格式化代碼(同級元素在自己的行上,每個層次結構都有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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM