3

私は AJAX を使用する Web サイトに取り組んでおり、行き止まりに遭遇しました。私の JavaScript には、validate という名前の関数があり、「name」フィールドと「password」フィールドを取得して、それを php に送信し、応答を待ちます。

function Validate() {
    var xmlhttp;
    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() {

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {

            if (xmlhttp.responseText.value == 'Invalid'){

                $("#box").effect('shake',150);  

                document.getElementById("validationText").innerHTML = xmlhttp.responseText;
            }
            else if (xmlhttp.reponseText.value == 'Success!'){  
            console.log(xmlhttp.responseText.value)
                document.getElementById("validationText").innerHTML = xmlhttp.responseText;


            }
        }
    }

    var name = document.getElementById("name").value;
    var password = document.getElementById("password").value;

    var arg = "JqueryPhp.php?name=" + name + "&password=" + password;

    xmlhttp.open("GET", arg, true);
    xmlhttp.send();
} 

PHP ファイルは、「Success!」のいずれかを返す必要があります。状況により「無効」となります。

<?php

    $con = mysql_connect("localhost","root","root");

    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

      mysql_select_db("collegedatabase", $con);

      $getUserName = $_GET["name"];
      $getPassword = $_GET["password"];

      $result = mysql_query("SELECT * FROM `admin`");
      $Success = false;

      /*    if the user entered does not exist, run the function which shakes the screen and add a bit of text to say that the username is invalid  */

        while ($row = mysql_fetch_array($result)){
            if ($row['userName'] == $getUserName && $row['password'] == $getPassword){
                echo "Success!";
                $Success = true;
                break;
            }
        }
        if($Success === false) {
            echo ('Invalid');
        }


    ?>

代わりに、body タグ内に文字列を含む html ファイル全体を返します。firebug から記録した応答は次のとおりです。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>



<body>

Invalid</body>

</html>
4

2 に答える 2

2

PHPexit;コードの最後に を追加します。

最後に、完全な html ページをレンダリングする何かが実行されている可能性があります。

于 2012-07-16T13:12:56.803 に答える
-5

Jquery 関数 $.POST を使用することをお勧めします

$.post("URL.php",{
       //Params(post)
    },
     function(data){
         //Answer  (data)
    })
于 2012-07-16T13:14:03.217 に答える