mcl*_*inj 756 javascript get http dashcode
我需要在JavaScript中执行HTTP GET请求.最好的方法是什么?
我需要在Mac OS X dashcode小部件中执行此操作.
小智 1146
您可以通过javascript使用托管环境提供的功能:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
Run Code Online (Sandbox Code Playgroud)
但是,不建议使用同步请求,因此您可能希望使用此命令:
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);
}
Run Code Online (Sandbox Code Playgroud)
注意:从Gecko 30.0(Firefox 30.0/Thunderbird 30.0/SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用.
Pis*_*tos 186
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
Run Code Online (Sandbox Code Playgroud)
tgg*_*gne 146
上面有很多很棒的建议,但不是很容易重复使用,而且经常充斥着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 );
}
}
Run Code Online (Sandbox Code Playgroud)
使用它就像:
var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
// do something with response
});
Run Code Online (Sandbox Code Playgroud)
Pet*_*son 102
新的window.fetchAPI是一个更清洁的替代品XMLHttpRequest,使用ES6承诺.有一个很好的解释在这里,但它归结为(文章):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
Run Code Online (Sandbox Code Playgroud)
浏览器支持现在在最新版本中很好(适用于Chrome,Firefox,Edge(v14),Safari(v10.1),Opera,Safari iOS(v10.3),Android浏览器和Android版Chrome),但IE将可能没有获得官方支持.GitHub有一个polyfill可用,建议支持仍在使用中的旧浏览器(特别是2017年3月的Safari和同期的移动浏览器).
我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质.
这是规范https://fetch.spec.whatwg.org/的链接
编辑:
使用ES7 async/await,这变得简单(基于此Gist):
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
Run Code Online (Sandbox Code Playgroud)
小智 89
没有回调的版本
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
Run Code Online (Sandbox Code Playgroud)
rp.*_*rp. 73
以下是使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*eón 35
复制粘贴就绪版本
//Option with catch
fetch( textURL )
.then(async r=> console.log(await r.text()))
.catch(e=>console.error('Boo...' + e));
//No fear...
(async () =>
console.log(
(await (await fetch( jsonURL )).json())
)
)();
Run Code Online (Sandbox Code Playgroud)
Dam*_*ica 23
短而纯:
const http = new XMLHttpRequest()
http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()
http.onload = () => console.log(http.responseText)Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom 19
IE将缓存URL以便加快加载速度,但是如果您在尝试获取新信息的同时轮询服务器,IE将缓存该URL并可能返回您一直拥有的相同数据集.
无论你最终如何做你的GET请求 - 香草JavaScript,原型,jQuery等 - 确保你建立了一个机制来对抗缓存.为了解决这个问题,请在您要点击的URL末尾附加一个唯一的令牌.这可以通过以下方式完成:
var sURL = '/your/url.html?' + (new Date()).getTime();
Run Code Online (Sandbox Code Playgroud)
这将在URL的末尾附加一个唯一的时间戳,并防止任何缓存发生.
Kam*_*ski 15
现代、干净、最短
fetch('https://www.randomtext.me/api/lorem')
Run Code Online (Sandbox Code Playgroud)
fetch('https://www.randomtext.me/api/lorem')
Run Code Online (Sandbox Code Playgroud)
let url = 'https://www.randomtext.me/api/lorem';
// to only send GET request without waiting for response just call
fetch(url);
// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));
// or async/await
(async()=>
console.log('\nREQUEST 3', await(await fetch(url)).json())
)();Run Code Online (Sandbox Code Playgroud)
Mar*_*iek 12
原型使它变得简单
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
Run Code Online (Sandbox Code Playgroud)
我不熟悉Mac OS Dashcode Widgets,但是如果他们让你使用JavaScript库并支持XMLHttpRequests,我会使用jQuery并执行以下操作:
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
Run Code Online (Sandbox Code Playgroud)
支持旧版浏览器的一种方案
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);
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
也许有点矫枉过正,但你肯定对这段代码安全.
用法:
//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();
Run Code Online (Sandbox Code Playgroud)
\n
我准备了一组函数,它们在某种程度上相似,但展示了新功能以及 Javascript 所达到的简单性(如果您知道如何利用它)。
\nlet data;\nconst URLAPI = "https://gorest.co.in/public/v1/users";\nfunction setData(dt) {\n data = dt;\n}\nRun Code Online (Sandbox Code Playgroud)\n// MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 1 --> ", data);\n data = null;\n });\n}\nRun Code Online (Sandbox Code Playgroud)\n// ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 2 --> ", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 3 --> ", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log("Data received 4 --> ", data);\n\n })\n}\nRun Code Online (Sandbox Code Playgroud)\n// ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\nRun Code Online (Sandbox Code Playgroud)\n值得一提 ---> @Daniel De Le\xc3\xb3n可能是最干净的函数*
\n(async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\nRun Code Online (Sandbox Code Playgroud)\n使用 Fetch 也可以实现同样的效果。根据MDN使用 Fetch展示了如何传递 INIT 作为第二个参数,基本上开启了使用经典方法(get、post...)轻松配置 API 的可能性。
\n// Example POST method implementation:\nasync function postData(url = \'\', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: \'POST\', // *GET, POST, PUT, DELETE, etc.\n mode: \'cors\', // no-cors, *cors, same-origin\n cache: \'no-cache\', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: \'same-origin\', // include, *same-origin, omit\n headers: {\n \'Content-Type\': \'application/json\'\n // \'Content-Type\': \'application/x-www-form-urlencoded\',\n },\n redirect: \'follow\', // manual, *follow, error\n referrerPolicy: \'no-referrer\', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match "Content-Type" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData(\'https://example.com/answer\', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\nRun Code Online (Sandbox Code Playgroud)\n获取在节点(服务器端)上不可用
\n最简单的解决方案(2021 年底)是使用Axios。
\n$ npm install axios\nRun Code Online (Sandbox Code Playgroud)\n然后运行:
\nconst axios = require(\'axios\');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\nRun Code Online (Sandbox Code Playgroud)\n
小智 6
现在有了异步js,我们可以将此方法与fetch()方法一起使用,使promise更加简洁。所有现代浏览器都支持异步函数。
async function funcName(url) {
const response = await fetch(url);
var data = await response.json();
}Run Code Online (Sandbox Code Playgroud)
您可以通过两种方式获取HTTP GET请求:
这种方法基于xml格式。您必须传递请求的URL。
xmlhttp.open("GET","URL",true);
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)这是基于jQuery的。您必须指定要调用的URL和function_name。
$("btn").click(function() {
$.ajax({url: "demo_test.txt", success: function_name(result) {
$("#innerdiv").html(result);
}});
});
Run Code Online (Sandbox Code Playgroud)对于那些使用AngularJs的人来说$http.get:
$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.
});
Run Code Online (Sandbox Code Playgroud)
为此,建议使用JavaScript Promises来获取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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1616862 次 |
| 最近记录: |