var XMLHttpRequestObject=false
if(window.XMLHttpRequest)
{
XMLHttpRequestObject=new XMLHttpRequest()
}
else if(window.ActiveXObject)
{
XMLHttpRequestObject=new ActiveXObject("Microsoft.XMLHTTP")
}
//以上代码是创建一个XMLHttpRequest对象
//下面是一个使用这个XMLHttpRequest对象的函数,这个函数获取服务器的一个文件内容并显示到网页
function getData(dataSource,divID)
{
if(XMLHttpRequestObject)
{
var obj=document.getElementById(divID)
XMLHttpRequestObject.open("GET",dataSource)
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
XMLHttpRequestObject.onreadystatechange=function ()
{
if(XMLHttpRequestObject.readyState==4 &&XMLHttpRequestObject.status==200)
{
obj.innerHTML=XMLHttpRequestObject.responseText
}
}
XMLHttpRequestObject.send(NULL)
}
}
</script>
以下是<body>代码
<body>
<H1>This is an ajax demo</H1>
<form>
<input type="button" value="Fetch the message" onclick="getData('data.txt','dataDiv')"/>
</form>
<div id="dataDiv">
<p>The fetch message will appear here</p>
</div>
</body>
你需要在当前页面文件夹下建一个data.txt文件、点击那个按钮、然后txt里的东西会显示在dataDiv的内容里面
<script type="text/javascript">//请求函数
function f1(){
console.log('start')
//1.创建AJAX对象
var ajax = new XMLHttpRequest()
//4.给AJAX设置事件(这里最多感知4[1-4]个状态)
ajax.onreadystatechange = function(){
//5.获取响应
//responseText 以字符串的形式接收服务器返回的信息
//console.log(ajax.readyState)
if(ajax.readyState == 4 && ajax.status == 200){
var msg = ajax.responseText
console.log(msg)
//alert(msg)
var divtag = document.getElementById('result')
divtag.innerHTML = msg
}
}
//2.创建http请求,并设置请求地址
var username = document.getElementsByTagName('input')[0].value
var email = document.getElementsByTagName('input')[1].value
username = encodeURIComponent(username) //对输入的特殊符号(&,=等)进行编码
email = encodeURIComponent(email)
ajax.open('get','response.php?username='+username+'&email='+email)
//3.发送请求(get--null post--数据)
ajax.send(null)
}
</script>
var xmlHttpfunction getIPByPHP(ip){
if (ip.length==0){
return
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var url="ip.php"
url=url+"?ip="+ip
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
var json = ""+xmlHttp.responseText
var obj = eval("(" + json + ")")
lat = obj.latitude//纬度
longitude = obj.longitude//经度
countryCode = obj.country_code
country = obj.country_name
city = obj.city
ip = obj.ip
ipLatLng = new google.maps.LatLng(lat,longitude)
chunZhenCountry = obj.chunzhen_country
chunZhenArea = obj.chunzhen_area
}
}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
}