我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
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/')
同样的事情也可以为post request做。 看看这个链接JavaScript post请求像一个表单提交
其他回答
为了刷新来自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();
});
}
这里有一个xml文件的替代方案,以非常快的方式将文件作为对象加载和访问属性作为对象。
注意,为了使javascript能够正确地解释内容,有必要将文件保存为与HTML页面相同的格式。如果你使用UTF8保存你的文件在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);
}
}
这只是给大家的一份小礼物。谢谢你的喜欢:)
如果您想在本地测试该功能,请使用以下命令重新启动浏览器(除safari外所有浏览器都支持):
yournavigator.exe '' --allow-file-access-from-files
要做到这一点,建议使用Fetch API,使用JavaScript Promises。XMLHttpRequest (XHR)、IFrame对象或动态<script>标记是较旧(且较笨重)的方法。
<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>
这里有一个很棒的获取演示和MDN文档
下面是直接用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;
}
}
}
最好的方法是使用AJAX(您可以在Tizag页面上找到一个简单的教程)。原因是你可能使用的任何其他技术都需要更多的代码,它不能保证在不返工的情况下跨浏览器工作,并且需要你通过在帧内打开隐藏页面传递url解析其数据并关闭它们来使用更多的客户端内存。 AJAX是解决这种情况的方法。这就是我两年的javascript重度开发讲的。