当前位置: 动力学知识库 > 问答 > 编程问答 >

php - XMLHttpRequest Error in passing value on url

问题描述:

Here I have two fields: name & password. I have been to trying to echo the value using XMLHttpRequest, but when I click submit, it only shows the name and not the password. Please help me find where I have gone wrong.

------------Index.html--------------

<html>

<head>

<title>Fist Ajax Application</title>

<script type="text/javascript">

function test(){

var xmlhttp;

if(window.XMLHttpRequest){

xmlhttp = new XMLHttpRequest();

}else{

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

var uname = document.getElementById('username').value;

var upassword = document.getElementById('userpassword').value;

xmlhttp.onreadystatechange = function(){

if(xmlhttp.readyState==4){

document.getElementById('results').innerHTML = xmlhttp.responseText;

}

}

url = "testform.php?name="+uname+"&password="+upassword;

xmlhttp.open("GET",url,true);

xmlhttp.send();

}

</script>

</head>

<body>

<table border="1">

<tr>

<td>Name:</td>

<td><input type="text" name="name" id="username" /></td>

</tr>

<tr>

<td>Password</td>

<td><input type="text" name="password" id="userpassword" /></td>

</tr>

</table>

<input type="button" value="suubmit" onClick="test()" />

<p><div id="results"> Results...</div></p>

</body>

</html>


-----------------Testform.php---------------

<?php

$name = $_GET['name'];

$password = $GET['password'];

echo $password."<br />";

echo $name."<br />";

?>

网友答案:

use $password = $_GET['password']; instead of $password = $GET['password'];

网友答案:

Two problems,

First: You were asking the DOM, to get the element while the page had not completed loading.

Second: is as the previous user pointed out. this $GET['password']; is invalid syntax:

Now, change your Ajax to:

<body>
<table border="1">
  <tr>
    <td>Name:</td>
    <td><input type="text" name="name" id="username" /></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input type="text" name="password" id="userpassword" /></td>
  </tr>
</table>
<input type="button" value="suubmit" onClick="test()" />
<p><div id="results"> Results...</div></p>

<script type="text/javascript">
function test(){
var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();     
    }else{      
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

var uname = document.getElementById('username').value;
var upassword = document.getElementById('userpassword').value;

    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4){
            document.getElementById('results').innerHTML = xmlhttp.responseText;    
        }

    }

xmlhttp.open("GET","testform.php?name="+uname+"&password="+upassword, true);
xmlhttp.send(); 
}

console.log(test())
</script>

And, your PHP file,

<?php
if(isset($_GET)): 
$name = $_GET['name'];
$password = $_GET['password'];

echo $password."<br />";
echo $name."<br />";


endif;

?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: