tree /var/www/html/ajax/
/var/www/html/ajax/
├── getuser.php
└── index.html
很简单的逻辑,index.html通过ajax,将数据发送到getuser.php,将数据库的查询结果传递到index.html里面。
已经调试成功。
index.html
<html>
<head>
</head>
<body>
<form>
Select a User:
<select name="users" id="user">
<option value="x1">x1</option>
<option value="x2">x2</option>
<option value="x3">x3</option>
</select>
</form>
<input type="button" value="search" id="search">
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
<script>
var xmlHttp
function showUser(){
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var mySelect = document.getElementById("user");
var index = mySelect.selectedIndex;
var str = mySelect.options[index].value;
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
ob = document.getElementById("search");
ob.addEventListener("click",showUser);
</script>
</body>
</html>
getuser.php
<?php
$q=$_GET["q"];
$dsn = "mysql:host=localhost;dbname=ajax";
$con = new PDO($dsn,"root","xxxx");
$query_check = "select * from person where `FirstName`='$q' ";
$result = $con->query($query_check);
$rows = $result->fetchAll();
print_r($rows);
?>
现在,我想将index.html里面的全部js代码,独立成一个js文件
形成下面的结构
tree /var/www/html/ajax/
/var/www/html/ajax/
├── getuser.php
├── index.html
└── selectuser.js
selectuser.js部分
var xmlHttp
function showUser(){
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var mySelect = document.getElementById("user");
var index = mySelect.selectedIndex;
var str = mySelect.options[index].value;
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
ob = document.getElementById("search");
ob.addEventListener("click",showUser);
就是将index.html里面的<script></script>之间的内容全部移到 selectuser.js
发现,这样做,无法正常运转。
请问,应当做哪些修改?
分离出来,在html中引入这个js文件报错?