자바스크립트로 HTTP GET 요청을 수행해야 합니다. 이를 수행하는 가장 좋은 방법은 무엇인가요?
Mac OS X 대시코드 위젯에서 이 작업을 수행해야 합니다.
브라우저 (및 대시코드) 은 스믈하트프리퀘스트 객체 데 사용할 수 있는 JavaScript 에서 HTTP 요청을 만듭니다.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
그러나 동기식 요청은 발령합니다 활동에 따라 경고에는 줄 예정이다.
>. 참고: 게코 (30.0 시몽키 2.27 / 파이어폭스 / 선더버드 30.0) 부터 30.0 주 , 동기식 요청률 사용되지 않는 스레드할 부정적인 영향을 미칠 수 있기 때문에 사용자 경험.
비동기 이벤트 핸들러를 요청 및 응답 인사이드라면 처리하십니까 만들어야 합니다.
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);
}
[In jQuery] (https://api.jquery.com/jQuery.get/):
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
많은 조언, 그리고 위에 매우 큰 것이 아니라 재사용 가능한 채워진 말도 안 되는 경우가 너무 쉽게 감춰집니다 부풀리고 있는 DOM 및 기타 코드.
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
});
새 ['빈다우스페치'] [1] '약속' 을 사용 ES6 스믈하트프리퀘스트 API 는 대한 교체품을 진행중이다. # 39 의 there& 좋은 설명 했지만, 결국 아래로 here 에서 문서):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
[브라우저 지원] [3] 이제 优秀 이번 릴리스에서와 (은 크롬, 파이어폭스, Edge (v14), 사파리 (v10.1), 오페라, 사파리, 크롬 브라우저와 안드로이드, iOS, 안드로이드 (v10.3) 에 대한) 공식 지원은 IE 는 그러나 프레젠테이션이든 않을 것으로 보인다. 깃허브 는 폴리필 를 사용할 수 있는 오래된 브라우저가 지원할 수 있는 권장됩니까 아직 대부분 사용 (esp 버전의 사파리 사전 3월 2017년, 모바일 브라우저 같은 기간에 비해).
아마 이 보다 더 편리하기 표시할지를 또는 스믈하트프리퀘스트 프로젝트의 특성에 따라 방관하겠나 포함한다.
단순히 기다리는 ES7 사용하여, 비동기식 / 따라 이 사진을) 이 됩니다.
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
[1]: https://developers.google.com/web/updates/2015/03/introduction-to-fetch = en hl?
[3]: http://caniuse.com/ # 성과 = 페치할
다음은 자바스크립트로 직접 수행하는 코드입니다. 하지만 앞서 언급했듯이 자바스크립트 라이브러리를 사용하는 것이 훨씬 낫습니다. 제가 가장 좋아하는 것은 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;
}
}
}
>. A 복사 붙여 넣기 최신 버전 (using 페치할 및 누르십시보 함수은) :
//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())
)
)();
>. 복사 붙여 넣기 한 클래식 버전:
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);
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
<! - 언어: > js 랭 -;
const http = new 스믈하트프리퀘스트 ()
하트피오픈 (" GET" https://api.lyrics.ovh/v1/toto/africa" ";;;) 하트피젠드 ()
스테퍼론로이드 > () =, = 콘솔드로그 (하트피레스폰스테스트)
끝 - < 스니핏 >;!
IE 는 url # 39 더 빠르게 하기 위해 캐시에는 로드중 신앙이니라 you& 말하도다 폴링하여 간격으로 새로운 정보를 얻으려고 하고, re, 서버, IE 는 해당 URL 과 동일한 데이터 집합을 you& # 39, ve 복귀하십시오 캐시에는 가능성이 있다고 판단했다.
Javascript 상관없이 jQuery, Prototype 어떻게 GET 요청을 수행하기 끝날 수 있도록 하고, 바닐라 등 - 수 있는 메커니즘을 전투 캐싱과는. 이를 위해 고유한 토큰인지 덮어쓰기/추가 전투 끝에 uirl you& # 39, re going to be 타격. 이 에 따라 수행할 수 있습니다.
var sURL = '/your/url.html?' + (new Date()).getTime();
이렇게 하면 덮어쓰기/추가 고유한 시간스탬프와 모든 캐싱과는 발생하지 않도록 끝까지 uirl 중단됩니다.
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
[2]: http://docs.jquery.com/Ajax/jQuery.get # 참조용이므로
지원하는 솔루션을 한 오래된 브라우저:
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);
}
}
};
}
아마 다소 오버킬 확장하지만 말해둘꼐요 gnu. 안전하다구요 대체하십시오 코드입니다.
< strong> Usage:< /strong>;;; < br>;
//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();
[앙굴라이스] [1], it& 사용하는 사람들을 위한 '$ # 39 의 하트피제':
$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.
});
[1]: https://docs.angularjs.org/api/ng/service/ $ http
이렇게 하려면 페치할 API 는 권장됨 외곽진입 JavaScript 를 사용하여 공약. 스믈하트프리퀘스트 객체 또는 동적 (스어), IFrame < script>; 태그는 tfsnap (및 클언크리에) 방식.
<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>
다음은 숭배자들로부터도 [페치할 데모] (https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data) 및 [매든 docs] (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
Ajax 를 사용하는 것이 가장 좋은 방법은 (rec.601 이 페이지에서 확인할 수 있는 간단한 자습서는 [티자크] [1]). 그 이유는 다른 기술을 사용할 수 있는 것은 더 필요한 코드를 보장할 수 없는 일을 더 많이 사용하는 브라우저 금지커서 프레임 안에 숨겨진 페이지 url 을 열어서 클라이언트 메모리 재작업 합니다 자신의 데이터를 파싱 및 닫기와 저들이요 반군지역 AJAX 는 이 길을 갈 것이다. 2 년 내 javascript 의 대규모 개발 이같이 말했습니다.
[1]: http://www.tizag.com/ " tizag";
Http GET 요청을 두 가지 방법으로 얻을 수 있습니다.
스믈하트피오픈 (,,, 참 " GET" " URL"). 스믈하트피젠드 ();
$ (" btn";) (함수 () {클릭하십시오. $ 지아이아스 ({url: demo_test.txt" ";, 성공을 거두었다. function_name (결과) { $ (", # innerdiv") .html (결과). }}); }).
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 를 수행할 수 있으며, 요구가 well.< br>, 같은 것입니다. 투명지에 이걸봐 https://partner. https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
간단한 비동기 http://competitivehelp
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();
}