Javascript页面发送凭据

时间:2011-08-28 15:13:26

标签: javascript xmlhttprequest

JavaScript文件

<html>
<head>
<script type="text/javascript">

function send()
{
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)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("POST","192.168.0.10/unp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(encodeURI("Username="+document.form1.uname.value+"&password="+document.form1.pass.value));





}

</script>
</head>

<body>

<form name="form1" method="post">
USERNAME:<input type = "text" name="uname"><br>
PASSWORD:<input type = "password" name="pass">


<br>



<input type="submit" onclick="send()">
</form>
<div id="myDiv"><p>How are You </p></div>
</body>
</html>

在服务器上运行的PHP文件。我想将凭证存储在服务器上的文件中

<?php
$myfile="testfile.txt";
$fh=fopen($myfile,'a');
$stringdata=$_POST["Username"];
$stringdata1=$_POST["password"];
fwrite($fh,$stringdata);
fwrite($fh,$stringdata1);
fclose($fh);
?>
<html>
Details Submitted
</html>

客户端页面加载时没有错误。然而,文件文件文件已创建。 响应也不会返回。 Js文件是否正确?

1 个答案:

答案 0 :(得分:1)

您是否希望“已提交详细信息”在屏幕上显示 ?从您的代码(看起来像当前文档)看来,您认为是这样,但不是,情况并非如此。该文本将在xmlhttp.responseText中,并在xmlhttp.responseXML中整齐地解析。

修改

Vinod的评论指出了他的代码中的一些其他错误,特别是他的编码错误(这可能不是他看到的问题)和标题丢失(可能是)。他本应写的:

var params = "Username="+encodeURIComponent(document.form1.uname.value)+
         "&password="+encodeURIComponent(document.form1.pass.value);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);