JavaScript 中的 HTTP GET 请求?
-
05-07-2019 - |
题
我需要做一个 HTTP 获取 JavaScript 中的请求。最好的方法是什么?
我需要在 Mac OS X dashcode 小部件中执行此操作。
解决方案
浏览器(和Dashcode)提供了一个XMLHttpRequest对象,可用于从JavaScript发出HTTP请求:
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)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用。
您应该发出异步请求并在事件处理程序中处理响应。
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);
}
其他提示
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
上面有很多很棒的建议,但不是非常可重复使用,而且经常充斥着DOM废话和其他隐藏简单代码的漏洞。
这是我们创建的一个可重用且易于使用的Javascript类。目前它只有一个GET方法,但这对我们有用。添加POST不应该对任何人的技能征税。
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
使用它就像:
var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
// do something with response
});
没有回调的版本
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
新的 window.fetch
API是使用ES6承诺的 XMLHttpRequest
的更干净的替代品。有一个很好的解释这里,但它归结为(来自文章):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
浏览器支持现在在最新版本中表现不错(适用于Chrome,Firefox,Edge(v14) ),Safari(v10.1),Opera,Safari iOS(v10.3),Android浏览器和Android版Chrome),但IE可能无法获得官方支持。 GitHub有一个polyfill ,建议用于支持仍在使用中的旧版浏览器(特别是Safari前三版本) 2017年和同期的移动浏览器。)
我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质。
以下是 https://fetch.spec.whatwg.org/ 的规范链接
修改强>:
使用ES7 async / await,这变得简单(基于这个要点):
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
以下是使用JavaScript直接执行此操作的代码。但是,如前所述,使用JavaScript库会更好。我最喜欢的是jQuery。
在下面的例子中,正在调用ASPX页面(作为穷人的REST服务进行服务)以返回JavaScript JSON对象。
var xmlHttp = null;
function GetCustomerInfo()
{
var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", Url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "Not found" )
{
document.getElementById( "TextBoxCustomerName" ).value = "Not found";
document.getElementById( "TextBoxCustomerAddress" ).value = "";
}
else
{
var info = eval ( "(" + xmlHttp.responseText + ")" );
// No parsing necessary with JSON!
document.getElementById( "TextBoxCustomerName" ).value = info.jsonData[ 0 ].cmname;
document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
}
}
}
复制粘贴就绪版
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
document.body.className = 'ok';
console.log(this.responseText);
} else if (this.response == null && this.status === 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url, true);
request.send(null);
IE会缓存网址以便加快加载速度,但如果你是在某个时间间隔轮询服务器试图获取新信息,那么IE会缓存该网址,并且可能会返回相同的数据集。了。
无论你最终如何做你的GET请求 - 香草JavaScript,原型,jQuery等 - 确保你建立了一个机制来对抗缓存。为了解决这个问题,请在您要点击的URL末尾附加一个唯一的令牌。这可以通过以下方式完成:
var sURL = '/your/url.html?' + (new Date()).getTime();
这将在URL的末尾附加一个唯一的时间戳,并防止任何缓存发生。
短而纯:
const http = new XMLHttpRequest()
http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()
http.onload = () => console.log(http.responseText)
Prototype 让它变得简单
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
我不熟悉Mac OS Dashcode Widgets,但如果他们允许您使用JavaScript库并支持 XMLHttpRequests ,我使用 jQuery 并执行类似这样的操作:
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
支持旧浏览器的一种解决方案:
function httpRequest() {
var ajax = null,
response = null,
self = this;
this.method = null;
this.url = null;
this.async = true;
this.data = null;
this.send = function() {
ajax.open(this.method, this.url, this.asnyc);
ajax.send(this.data);
};
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch(e) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch(error) {
self.fail("not supported");
}
}
}
if(ajax == null) {
return false;
}
ajax.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
self.success(this.responseText);
}
else {
self.fail(this.status + " - " + this.statusText);
}
}
};
}
可能有点矫枉过正,但你肯定对这段代码保持安全。
<强>用法:强> 结果
//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";
//create callback for success containing the response
request.success = function(response) {
console.log(response);
};
//and a fail callback containing the error
request.fail = function(error) {
console.log(error);
};
//and finally send it away
request.send();
在小部件的Info.plist文件中,不要忘记将 AllowNetworkAccess
键设置为true。
最好的方法是使用AJAX(您可以在此页面上找到一个简单的教程 Tizag )。原因是您可能使用的任何其他技术都需要更多代码,不能保证在没有返工的情况下跨浏览器工作,并且需要通过在框架内打开隐藏页面来传递URL来解析数据并关闭它们来使用更多客户端内存。 AJAX是这种情况下的方法。那我的两年javascript开发说话。
对于那些使用 AngularJs 的人来说,这是 $ http 。获得代码>:
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
您可以通过两种方式获取HTTP GET请求:
-
这种方法基于xml格式。您必须传递请求的URL。
xmlhttp.open("GET","URL",true); xmlhttp.send();
-
这个基于jQuery。您必须指定要调用的URL和function_name。
$("btn").click(function() { $.ajax({url: "demo_test.txt", success: function_name(result) { $("#innerdiv").html(result); }}); });
醇>
function get(path) {
var form = document.createElement("form");
form.setAttribute("method", "get");
form.setAttribute("action", path);
document.body.appendChild(form);
form.submit();
}
get('/my/url/')
也可以为帖子请求做同样的事情。
请查看此链接 JavaScript发布请求,如表单提交
为此,使用JavaScript Promises建议使用Fetch API。 XMLHttpRequest(XHR),IFrame对象或动态标签是较旧(和笨重)的方法。
<script type=“text/javascript”>
// Create request object
var request = new Request('https://example.com/api/...',
{ method: 'POST',
body: {'name': 'Klaus'},
headers: new Headers({ 'Content-Type': 'application/json' })
});
// Now use it!
fetch(request)
.then(resp => {
// handle response })
.catch(err => {
// handle errors
}); </script>
简单的异步请求:
function get(url, callback) {
var getRequest = new XMLHttpRequest();
getRequest.open("get", url, true);
getRequest.addEventListener("readystatechange", function() {
if (getRequest.readyState === 4 && getRequest.status === 200) {
callback(getRequest.responseText);
}
});
getRequest.send();
}
如果您想使用Dashboard小部件的代码,并且您不想在您创建的每个小部件中包含JavaScript库,那么您可以使用Safari本机支持的对象XMLHttpRequest。
据Andrew Hedges报道,默认情况下,窗口小部件无权访问网络;您需要在与小部件关联的info.plist中更改该设置。
要刷新joann的最佳答案,这是我的代码:
let httpRequestAsync = (method, url) => {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.responseText);
}
else {
reject(new Error(xhr.responseText));
}
};
xhr.send();
});
}
你也可以用纯JS做到这一点:
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
请参阅:了解更多详情: html5rocks tutorial
这是 xml 文件的替代方案,可以以非常快速的方式将文件作为对象加载并作为对象访问属性。
- 注意,为了让 javascript 能够正确解释内容,有必要以与 HTML 页面相同的格式保存文件。如果您使用 UTF 8 将文件保存为 UTF8 等。
XML 可以像树一样工作吗?而不是写作
<property> value <property>
编写一个简单的文件,如下所示:
Property1: value
Property2: value
etc.
保存您的文件..现在调用该函数....
var objectfile = {};
function getfilecontent(url){
var cli = new XMLHttpRequest();
cli.onload = function(){
if((this.status == 200 || this.status == 0) && this.responseText != null) {
var r = this.responseText;
var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
if(b.length){
if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
r=j.split(b);
r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
r = r.map(f => f.trim());
}
if(r.length > 0){
for(var i=0; i<r.length; i++){
var m = r[i].split(':');
if(m.length>1){
var mname = m[0];
var n = m.shift();
var ivalue = m.join(':');
objectfile[mname]=ivalue;
}
}
}
}
}
cli.open("GET", url);
cli.send();
}
现在您可以有效地获取您的价值观。
getfilecontent('mesite.com/mefile.txt');
window.onload = function(){
if(objectfile !== null){
alert (objectfile.property1.value);
}
}
这只是为团体做贡献的一份小礼物。谢谢你的喜欢:)
如果您想在本地PC上测试该功能,请使用以下命令重新启动浏览器(除safari之外的所有浏览器都支持):
yournavigator.exe '' --allow-file-access-from-files