1 <body> 2 <center> 3 <form> 4 <br/> 5 <div id="show"></div> 6 用户名: 7 <input type="text" name="userName" /> <br/> <br/> 8 密 码: 9 <input type="password" name="password" /> <br/><br/> 10 <button name="login" id="id_login" onClick="loginAction()">登录 </button> 11 <br/> 12 13 </form> 14 </center> 15 <script src="fun/MyUtils.js"> </script> 16 <script type="text/javascript"> 17 //登录处理事件 18 function loginAction() { 19 20 var userName = document.getElementsByName("userName").value; 21 var password = document.getElementsByName("password").value; 22 var xmlHttp; 23 try 24 { 25 // Firefox, Opera 8.0+, Safari 26 xmlHttp = new XMLHttpRequest(); 27 } 28 catch (e) 29 { 30 // Internet Explorer 31 try { 32 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 33 } 34 catch (e) 35 { 36 try { 37 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 38 } 39 catch (e) { 40 alert("您的浏览器不支持AJAX!"); 41 return false; 42 } 43 } 44 } 45 46 xmlHttp.onreadystatechange = function() 47 { 48 if (xmlHttp.readyState == 4) 49 { 50 //alert(xmlHttp.responseText); 51 var str = xmlHttp.responseText; 52 document.getElementById('show').innerHTML =str; 53 //alert(str); 54 var obj = eval('('+ xmlHttp.responseText +')'); 55 56 alert(obj); 57 } 58 } 59 60 xmlHttp.open("POST", "testJson.php", true); 61 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 62 xmlHttp.send("user=" . userName); 63 xmlHttp.send("pass=" . password); 64 } 65 </script> 66 </body>
下面是php源码
<?php $res['id'] = $_POST['user']; $res['name'] = "elar"; $res['age'] = "21"; echo json_encode($res); ?>
为什么js接受不到php传来的数据?
本人初学web。请麻烦直接指出错误。我照着网上的例子可以得到返回的值,但只要稍微修改就不行了。谢谢
62 xmlHttp.send("user=" . userName);
63 xmlHttp.send("pass=" . password);
就算能成功也会发送两次啊,你还是把参数写到URL里吧