我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
原型让它变得非常简单
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
其他回答
没有回调的版本
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
我不熟悉Mac OS的Dashcode小部件,但如果他们让你使用JavaScript库和支持xmlhttprequest,我会使用jQuery,做这样的事情:
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
短的、干净的:
const http = new XMLHttpRequest() http。打开(“得到”,“https://api.lyrics.ovh/v1/toto/africa”) http.send () http。onload = () => console.log(http.response)
现代、干净、简洁
fetch('https://baconipsum.com/api/?type=1')
让url = 'https://baconipsum.com/api/?type=all-meat¶s=1&start-with-lorem=2'; //只发送GET请求而不等待响应 fetch (url); //使用then来等待结果 获取(url)。然后(r = > r.json()。then(j=> console.log('\nREQUEST 2',j))); //或async/await (异步()= > console.log('\nREQUEST 3', await(await fetch(url)).json()) ) (); 打开Chrome控制台网络选项卡查看请求
你可以通过两种方式获得HTTP get请求:
该方法基于xml格式。您必须为请求传递URL。 xmlhttp.open(“获得”、“URL”,真正的); xmlhttp.send (); 它是基于jQuery的。您必须指定要调用的URL和function_name。 $ (btn) .click(函数(){ 美元。Ajax ({url: "demo_test.txt", success: function_name(result) { $ (" # innerdiv ") . html(结果); }}); });