浏览器(和Dashcode)提供可用于从JavaScript发出HTTP请求的XMLHttpRequest对象:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
但是,不鼓励同步请求,并将生成以下警告:
注意:从Gecko 30.0(Firefox 30.0/Thunderbird 30.0/SeaMonkey 2.27)开始,synchronous requests on the main thread have been deprecated是因为对用户体验的负面影响.
您应该发出异步请求,并在事件处理程序中处理响应.
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}