如何用JS请求HTTP

JavaScript015

如何用JS请求HTTP,第1张

其实你完全可以采用jquery的ajax方式来读取.var result = false

var thenow = new Date()

$.ajax({

type:"POST",

url:"此处为相对路径的php文件?Time="+thenow.getMilliseconds()+"M"+thenow.getSeconds()+"",

data:{id:id},

success:function(data){

}

})

如果你不用jquery

 var xmlHttps = new Array(10) 

 var e

 var EndHtml=false

 

 //创建XMLHTTP对象

 function getXMLHTTPObj()

 {

  var C = null

  try

  {

    C = new ActiveXObject("Microsoft.XMLHTTP")

  }

  catch(e)

  {

   try

   {

    C = new ActiveXObject("Msxml2.XMLHTTP")  

   }

   catch(sc)

   {

    C = null

   }

  }

  

  if( !C && typeof XMLHttpRequest != "undefined" )

  {

   C = new XMLHttpRequest()

  }

  

  return C

 }

 

 function GetDetail(userid,id) 

 { 

   

  document.getElementById(id).innerHTML = ""

  

   

  try

  { 

   xmlHttps[id]=false

   xmlHttps[id]= getXMLHTTPObj()

   if( xmlHttps[id] )

   {

     

  

  var realUrl = "/Ajax.aspx?action="+id+"&userid=" + escape(userid)+"&date="+new Date().getTime()

 

 

    xmlHttps[id].open("get", realUrl, true)

    //设置回调函数

    xmlHttps[id].onreadystatechange = function(){updatePage(id,xmlHttps[id])} 

    //发送请求

    xmlHttps[id].send(null)

   // xmlHttps.abort()   

   }

   else

   {

   

  document.getElementById(id).innerHTML = "<font color=#ff0000>×</font>您的浏览器不支持"

   }

  }

  catch (e)

  {

  

  document.getElementById(id).innerHTML = "<font color=#ff0000>×</font> 发生异常"

  

  }

 }

在Web项目中,有时需要通过协议调取来自其他环境的数据。HTTPS是一种应用于安全数据传输的网络协议。我们都知道Ajax可以异步请求数据,但单单通过ajax无法实现跨域。采用一些其他方式需要根据不同的浏览器做相应处理,火狐,谷歌等和IE需要各自做相应判断,所以这种通过浏览器来解析数据虽然省略了数据的解压缩等处理,但是在有安全认证等情况下做跨域处理确比较困难。比如:IE的请求Header无法更改。这时通过Node请求并解析数据就显得比较简单了。如下是nodejs中通过https请求数据的全过程:

var https = require('https')

var zlib = require('zlib')

var post_data="………………"//请求数据

var reqdata = JSON.stringify(post_data)

var options = {

   hostname: '10.225.***.***',

   port: '8443',

   path: '/data/table/list',

   method: 'POST',

   rejectUnauthorized: false,

   requestCert: true,

   auth: 'admin:123456************',

   headers: {

       'username': 'admin',

       'password': '123456************',

       'Cookie': 'locale=zh_CN',

       'X-BuildTime': '2015-01-01 20:04:11',

       'Autologin': '4',

       'Accept-Encoding': 'gzip, deflate',

       'X-Timeout': '3600000',

       'Content-Type': 'Application/json',

       "Content-Length":reqdata.length

   }

}

var req = https.request(options, function (res) {

})

req.write(reqdata)

req.on('response', function (response) {

   switch (response.headers['content-encoding']) {

       case 'gzip':

           var body = ''

           var gunzip = zlib.createGunzip()

           response.pipe(gunzip)

           gunzip.on('data', function (data) {

               body += data

           })

           gunzip.on('end', function () {

               var returndatatojson= JSON.parse(body)

               req.end()

           })

           gunzip.on('error', function (e) {

               console.log('error' + e.toString())

               req.end()

           })

           break

       case 'deflate':

           var output = fs.createWriteStream("d:temp.txt")

           response.pipe(zlib.createInflate()).pipe(output)

           req.end()

           break

       default:req.end()

           break

   }

})

req.on('error', function (e) {

   console.log(new Error('problem with request: ' + e.message))

   req.end()

   setTimeout(cb, 10)

})

注:options,需要有请求数据的长度,options需要加上'Accept-Encoding': 'gzip, deflate',返回的数据需要判断是哪种压缩方式,然后解压缩获取到数据。gunzip的end事件里的returndatatojson即是获取的数据。