HTTP GET request in JavaScript? - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript: function httpGet(theUrl) { var xmlHttp ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HTTPGETrequestinJavaScript? AskQuestion Asked 13years,4monthsago Modified 29daysago Viewed 2.3mtimes 979 277 IneedtodoanHTTPGETrequestinJavaScript.What'sthebestwaytodothat? IneedtodothisinaMacOSXdashcodewidget. javascripthttp-getdashcode Share Follow editedSep28,2020at16:19 JonSchneider 23.2k1818goldbadges136136silverbadges162162bronzebadges askedOct29,2008at16:31 mclaughjmclaughj 11.8k44goldbadges3030silverbadges3737bronzebadges 1 14 NotethatthisissubjecttotheSameOriginPolicy.en.wikipedia.org/wiki/Same_origin_policy – ripper234 Oct6,2011at21:10 Addacomment  |  30Answers 30 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 1401 Browsers(andDashcode)provideanXMLHttpRequestobjectwhichcanbeusedtomakeHTTPrequestsfromJavaScript: functionhttpGet(theUrl) { varxmlHttp=newXMLHttpRequest(); xmlHttp.open("GET",theUrl,false);//falseforsynchronousrequest xmlHttp.send(null); returnxmlHttp.responseText; } However,synchronousrequestsarediscouragedandwillgenerateawarningalongthelinesof: Note:StartingwithGecko30.0(Firefox30.0/Thunderbird30.0/SeaMonkey2.27),synchronousrequestsonthemainthreadhavebeendeprecatedduetothenegativeeffectstotheuserexperience. Youshouldmakeanasynchronousrequestandhandletheresponseinsideaneventhandler. functionhttpGetAsync(theUrl,callback) { varxmlHttp=newXMLHttpRequest(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200) callback(xmlHttp.responseText); } xmlHttp.open("GET",theUrl,true);//trueforasynchronous xmlHttp.send(null); } Share Follow editedApr3,2019at15:43 Quentin 847k117117goldbadges11401140silverbadges12561256bronzebadges answeredOct27,2010at12:43 JoanJoan 14.1k22goldbadges1414silverbadges22bronzebadges 12 2 Well,ofcourseJavascripthasitbuiltin,orhowcouldanyJavascriptlibraryofferaconveniencemethodforit?Thedifferencebeingthattheconveniencemethodsoffer,well,convenience,andaclearer,simplersyntax. – Pistos Jun26,2014at19:53 14 XMLprefixbecauseitusestheXfromAJAX~AsynchronousJavaScriptandXML.Also,goodpointrethe"APIthathasandECMAScriptbinding"isduetothefactthatJavaScriptcanbeinmanythings,otherthanbrowserssupportingHTTP(e.g.likeAdobeReader...)Goodthingtoremembersohats-offtoPointedEars. – will Sep5,2014at4:29 9 @AlikElzin-kilakaActuallyalltheanswersaboveareoffthemark(infactthelinkedW3docsexplains"eachcomponentofthisnameispotentiallymisleading").Correctanswer?itsjustbadlynamedstackoverflow.com/questions/12067185/… – AshleyCoolman May28,2016at11:58 2 whydoweneedtoxmlHttp.send(null);.whatdoesitmean? – Tan-007 May14,2019at17:32 4 ThefetchAPIoffersabetterwaytodothis,andcanbepolyfilledwhennecessary(see@PeterGibson'sanswerbelow). – Dominus.Vobiscum Oct12,2019at17:33  |  Show7morecomments 216 Thenewwindow.fetchAPIisacleanerreplacementforXMLHttpRequestthatmakesuseofES6promises.There'saniceexplanationhere,butitboilsdownto(fromthearticle): fetch(url).then(function(response){ returnresponse.json(); }).then(function(data){ console.log(data); }).catch(function(){ console.log("Booo"); }); Browsersupportisnowgoodinthelatestreleases(worksinChrome,Firefox,Edge(v14),Safari(v10.1),Opera,SafariiOS(v10.3),Androidbrowser,andChromeforAndroid),howeverIEwilllikelynotgetofficialsupport.GitHubhasapolyfillavailablewhichisrecommendedtosupportolderbrowsersstilllargelyinuse(espversionsofSafaripreMarch2017andmobilebrowsersfromthesameperiod). IguesswhetherthisismoreconvenientthanjQueryorXMLHttpRequestornotdependsonthenatureoftheproject. Here'salinktothespechttps://fetch.spec.whatwg.org/ Edit: UsingES7async/await,thisbecomessimply(basedonthisGist): asyncfunctionfetchAsync(url){ letresponse=awaitfetch(url); letdata=awaitresponse.json(); returndata; } Share Follow editedFeb20,2018at22:58 answeredJul11,2016at0:45 PeterGibsonPeterGibson 17.8k66goldbadges5757silverbadges6262bronzebadges 2 11 Imightsavesomeonesometimebymentioningthatyoucandothistoincludecredentialsintherequest:fetch(url,{credentials:"include"}) – Enselic Mar9,2017at11:01 @bugmenot123window.fetchdoesn'tcomewithanXMLparser,butyoucanparsetheresponseyourselfifyouhandleitastext(notjsonasintheexampleabove).Seestackoverflow.com/a/37702056/66349foranexample – PeterGibson Aug16,2017at22:56 Addacomment  |  208 InjQuery: $.get( "somepage.php", {paramOne:1,paramX:'abc'}, function(data){ alert('pagecontent:'+data); } ); Share Follow editedJun24,2019at15:42 answeredOct29,2008at16:38 PistosPistos 22k1414goldbadges6161silverbadges7575bronzebadges 4 5 notethatthisisn'tworkinginIE10whentryingtoaccessurlinadifferentdomainthanthepage'sdomain – BornToCode Sep30,2013at9:35 6 @BornToCodeyoushouldinvestigatefurtherandpossiblyopenupabugonthejQueryissuetrackerinthatcase – ashes999 Oct8,2013at16:58 113 IknowsomepeoplewanttowritepureJavascript.Igetthat.Ihavenoproblemwithpeopledoingthatintheirprojects.My"InjQuery:"shouldbeintpretedas"IknowyouaskedhowtodoitinJavascript,butletmeshowyouhowyouwoulddothatwithjQuery,thatyoumighthaveyourcuriositypiquedbyseeingwhatkindofsyntaxconcisenessandclarityyoucanenjoybyusingthislibrary,whichwouldaffordyounumerousotheradvantagesandtoolsaswell". – Pistos Jun26,2014at19:47 43 Observealsothattheoriginalposterlatersaid:"Thanksforalltheanswers!IwentwithjQuerybasedonsomethingsIreadontheirsite.". – Pistos Jun26,2014at19:49 Addacomment  |  174 Lotsofgreatadviceabove,butnotveryreusable,andtoooftenfilledwithDOMnonsenseandotherfluffthathidestheeasycode. Here'saJavascriptclasswecreatedthat'sreusableandeasytouse.CurrentlyitonlyhasaGETmethod,butthatworksforus.AddingaPOSTshouldn'ttaxanyone'sskills. varHttpClient=function(){ this.get=function(aUrl,aCallback){ varanHttpRequest=newXMLHttpRequest(); anHttpRequest.onreadystatechange=function(){ if(anHttpRequest.readyState==4&&anHttpRequest.status==200) aCallback(anHttpRequest.responseText); } anHttpRequest.open("GET",aUrl,true); anHttpRequest.send(null); } } Usingitisaseasyas: varclient=newHttpClient(); client.get('http://some/thing?with=arguments',function(response){ //dosomethingwithresponse }); Share Follow editedDec14,2016at20:17 Ekevoo 2,63411goldbadge2121silverbadges3434bronzebadges answeredFeb27,2014at18:03 tggagnetggagne 2,79411goldbadge1919silverbadges1515bronzebadges 4 UnCaughtReferenceerror,HttpClientisnotdefined.Iamgettingthisonefirstlineitself. – sashikanta Jan10,2017at13:17 HowdoyoucallitfromhtmlonClick? – Gobliins Jan18,2017at10:39 Makeafunctionelsewherethatcontainsthevarclient...andjustrunfunctionName();returnfalse;intheonClick – mail929 Feb4,2017at20:48 3 ReferenceError:XMLHttpRequestisnotdefined – BugsBuggy Jul5,2017at19:48 Addacomment  |  101 Aversionwithoutcallback vari=document.createElement("img"); i.src="/your/GET/url?params=here"; Share Follow answeredNov8,2010at9:50 aNieto2kaNieto2k 1,01111goldbadge77silverbadges22bronzebadges 5 2 Excellent!IneededaGreasemonkeyscripttokeepasessionaliveandthissnippetisperfect.JustwrappeditinansetIntervalcall. – Carcamano Oct20,2016at14:33 9 howdoIgettheresult? – OMRYVOLK Nov16,2016at17:19 2 @user4421975Youdon'tget-togetaccesstorequestresponse,youneedtouseaforementionedXMLHttpRequestinstead. – JakubPastuszuk Apr4,2019at13:33 IthinkwecanevendowithoutJS – FLAW Feb10at13:24 @OMRYVOLKthat'stheneatpart,youdon't – FLAW Feb10at13:25 Addacomment  |  75 HereiscodetodoitdirectlywithJavaScript.But,aspreviouslymentioned,you'dbemuchbetteroffwithaJavaScriptlibrary.MyfavoriteisjQuery. Inthecasebelow,anASPXpage(that'sservicingasapoorman'sRESTservice)isbeingcalledtoreturnaJavaScriptJSONobject. varxmlHttp=null; functionGetCustomerInfo() { varCustomerNumber=document.getElementById("TextBoxCustomerNumber").value; varUrl="GetCustomerInfoAsJson.aspx?number="+CustomerNumber; xmlHttp=newXMLHttpRequest(); xmlHttp.onreadystatechange=ProcessRequest; xmlHttp.open("GET",Url,true); xmlHttp.send(null); } functionProcessRequest() { if(xmlHttp.readyState==4&&xmlHttp.status==200) { if(xmlHttp.responseText=="Notfound") { document.getElementById("TextBoxCustomerName").value="Notfound"; document.getElementById("TextBoxCustomerAddress").value=""; } else { varinfo=eval("("+xmlHttp.responseText+")"); //NoparsingnecessarywithJSON! document.getElementById("TextBoxCustomerName").value=info.jsonData[0].cmname; document.getElementById("TextBoxCustomerAddress").value=info.jsonData[0].cmaddr1; } } } Share Follow editedSep16,2013at8:33 user155407 answeredOct29,2008at16:35 rp.rp. 17.2k1111goldbadges6060silverbadges7878bronzebadges 2 37 Sincethisanswerisoneofthetopresultsforgoogling"httprequestjavascript",it'sworthmentioningthatrunningevalontheresponsedatalikethatisconsideredbadpractice – Kloar May19,2014at9:47 12 @Kloargoodpoint,butitwouldbeevenbettertogivethereasonwhyit'sbad,whichIguessissecurity.Explainingwhypracticesarebadisthebestwaytomakepeopleswitchtheirhabits. – Balmipour Sep16,2015at11:16 Addacomment  |  59 Acopy-pastemodernversion(usingfetchandarrowfunction): //Optionwithcatch fetch(textURL) .then(asyncr=>console.log(awaitr.text())) .catch(e=>console.error('Boo...'+e)); //Nofear... (async()=> console.log( (await(awaitfetch(jsonURL)).json()) ) )(); Acopy-pasteclassicversion: letrequest=newXMLHttpRequest(); request.onreadystatechange=function(){ if(this.readyState===4){ if(this.status===200){ document.body.className='ok'; console.log(this.responseText); }elseif(this.response==null&&this.status===0){ document.body.className='erroroffline'; console.log("Thecomputerappearstobeoffline."); }else{ document.body.className='error'; } } }; request.open("GET",url,true); request.send(null); Share Follow editedOct15,2019at18:01 answeredAug18,2014at7:23 DanielDeLeónDanielDeLeón 12.4k55goldbadges7878silverbadges6969bronzebadges Addacomment  |  47 Shortandclean: consthttp=newXMLHttpRequest() http.open("GET","https://api.lyrics.ovh/v1/toto/africa") http.send() http.onload=()=>console.log(http.responseText) Share Follow editedSep15,2019at15:18 answeredOct28,2017at18:42 DamianPavlicaDamianPavlica 25.4k77goldbadges6464silverbadges7171bronzebadges 2 Whatdoesthatlastline,specificallythe=()=>do? – SwimBikeRun May22,2021at19:28 2 Lastlinedefinesacallbackfunction,toexecutewhenserverresposeisloaded. – DamianPavlica May23,2021at22:16 Addacomment  |  23 IEwillcacheURLsinordertomakeloadingfaster,butifyou're,say,pollingaserveratintervalstryingtogetnewinformation,IEwillcachethatURLandwilllikelyreturnthesamedatasetyou'vealwayshad. RegardlessofhowyouendupdoingyourGETrequest-vanillaJavaScript,Prototype,jQuery,etc-makesurethatyouputamechanisminplacetocombatcaching.Inordertocombatthat,appendauniquetokentotheendoftheURLyou'regoingtobehitting.Thiscanbedoneby: varsURL='/your/url.html?'+(newDate()).getTime(); ThiswillappendauniquetimestamptotheendoftheURLandwillpreventanycachingfromhappening. Share Follow editedSep12,2015at1:01 Arend 3,69822goldbadges2525silverbadges3737bronzebadges answeredOct29,2008at16:40 TomTom 14.6k55goldbadges4646silverbadges6161bronzebadges Addacomment  |  19 Modern,cleanandshortest fetch('https://www.randomtext.me/api/lorem') leturl='https://www.randomtext.me/api/lorem'; //toonlysendGETrequestwithoutwaitingforresponsejustcall fetch(url); //towaitforresultsuse'then' fetch(url).then(r=>r.json().then(j=>console.log('\nREQUEST2',j))); //orasync/await (async()=> console.log('\nREQUEST3',await(awaitfetch(url)).json()) )(); OpenChromeconsolenetworktabtoseerequest Share Follow editedSep7,2020at12:00 answeredMay12,2020at11:20 KamilKiełczewskiKamilKiełczewski 68.2k2626goldbadges315315silverbadges284284bronzebadges 2 ShouldbementionedfetchnotsupportedbyanyIE-MDNdocs(ifanyonecaresaboutIEin2021) – BlueBot May12,2021at8:30 6 2021:whatisIE? – KamilKiełczewski Jul15,2021at15:57 Addacomment  |  14 Prototypemakesitdeadsimple newAjax.Request('/myurl',{ method:'get', parameters:{'param1':'value1'}, onSuccess:function(response){ alert(response.responseText); }, onFailure:function(){ alert('ERROR'); } }); Share Follow answeredOct29,2008at16:35 MarkBiekMarkBiek 140k5353goldbadges153153silverbadges198198bronzebadges 2 2 TheproblemisthatMacOSXdoesn'tcomewithPrototypepre-installed.Asthewidgetneedstoruninanycomputer,includingPrototype(orjQuery)ineachwidgetisnotthebestsolution. – apaderno Aug7,2010at5:05 @kiamlalunousePrototypecdnfromcloudflare – VladimirStazhilov Feb14,2017at10:34 Addacomment  |  13 Onesolutionsupportingolderbrowsers: functionhttpRequest(){ varajax=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=newXMLHttpRequest(); } elseif(window.ActiveXObject){ try{ ajax=newActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e){ try{ ajax=newActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(error){ self.fail("notsupported"); } } } if(ajax==null){ returnfalse; } ajax.onreadystatechange=function(){ if(this.readyState==4){ if(this.status==200){ self.success(this.responseText); } else{ self.fail(this.status+"-"+this.statusText); } } }; } Maybesomewhatoverkillbutyoudefinitelygosafewiththiscode. Usage: //createrequestwithitsporperties varrequest=newhttpRequest(); request.method="GET"; request.url="https://example.com/api?parameter=value"; //createcallbackforsuccesscontainingtheresponse request.success=function(response){ console.log(response); }; //andafailcallbackcontainingtheerror request.fail=function(error){ console.log(error); }; //andfinallysenditaway request.send(); Share Follow editedAug17,2018at12:03 answeredJul20,2016at11:23 user5862399user5862399 3 3 CouldpeoplepleasegivesomecommentsaboutwhatIhavedonewrong?Notveryhelpfulinthatway! – user5862399 Oct15,2016at14:04 Thebestanswerinmyopinion,ifoneiscodinginES5usingplainjavascript. – CoderX Aug9,2017at14:26 @CoderXnobodyiscodinginplainES5JavaScriptanymorethesedays.WehaveverygoodtranspilerslikeBabelforthat. – ThaJay Oct7,2021at7:59 Addacomment  |  10 TodothisFetchAPIistherecommendedapproach,usingJavaScriptPromises.XMLHttpRequest(XHR),IFrameobjectordynamic HereisagreatfetchdemoandMDNdocs Share Follow editedFeb21at12:06 lin 17.3k44goldbadges5353silverbadges8282bronzebadges answeredJul11,2018at21:51 aabiroaabiro 2,72211goldbadge2020silverbadges3434bronzebadges Addacomment  |  9 I'mnotfamiliarwithMacOSDashcodeWidgets,butiftheyletyouuseJavaScriptlibrariesandsupportXMLHttpRequests,I'dusejQueryanddosomethinglikethis: varpage_content; $.get("somepage.php",function(data){ page_content=data; }); Share Follow editedJan27,2014at14:27 PeterMortensen 29.8k2121goldbadges9898silverbadges124124bronzebadges answeredOct30,2008at4:03 DanielBeardsleyDanielBeardsley 19.1k2020goldbadges6363silverbadges7878bronzebadges Addacomment  |  6 Inyourwidget'sInfo.plistfile,don'tforgettosetyourAllowNetworkAccesskeytotrue. Share Follow answeredOct29,2008at19:42 AndrewHedgesAndrewHedges 21.4k1616goldbadges6464silverbadges7979bronzebadges Addacomment  |  6 ForthosewhouseAngularJs,it's$http.get: $http.get('/someUrl'). success(function(data,status,headers,config){ //thiscallbackwillbecalledasynchronously //whentheresponseisavailable }). error(function(data,status,headers,config){ //calledasynchronouslyifanerroroccurs //orserverreturnsresponsewithanerrorstatus. }); Share Follow answeredMay6,2015at20:36 VitaliiFedorenkoVitaliiFedorenko 103k2828goldbadges147147silverbadges111111bronzebadges Addacomment  |  6 YoucangetanHTTPGETrequestintwoways: Thisapproachbasedonxmlformat.YouhavetopasstheURLfortherequest. xmlhttp.open("GET","URL",true); xmlhttp.send(); ThisoneisbasedonjQuery.YouhavetospecifytheURLandfunction_nameyouwanttocall. $("btn").click(function(){ $.ajax({url:"demo_test.txt",success:function_name(result){ $("#innerdiv").html(result); }}); }); Share Follow editedApr3,2016at17:11 apaderno 26.4k1616goldbadges7474silverbadges8686bronzebadges answeredSep26,2014at13:21 parag.raneparag.rane 13911silverbadge66bronzebadges Addacomment  |  5 ThebestwayistouseAJAX(youcanfindasimpletutorialonthispageTizag).Thereasonisthatanyothertechniqueyoumayuserequiresmorecode,itisnotguaranteedtoworkcrossbrowserwithoutreworkandrequiresyouusemoreclientmemorybyopeninghiddenpagesinsideframespassingurlsparsingtheirdataandclosingthem. AJAXisthewaytogointhissituation.Thatmytwoyearsofjavascriptheavydevelopmentspeaking. Share Follow answeredOct29,2008at23:01 NikolaStjeljaNikolaStjelja 3,64999goldbadges3636silverbadges4545bronzebadges Addacomment  |  5 nowwithasynchronusjswecanusethismethodwithfetch()methodtomakepromisesinamoreconciseway.Asyncfunctionsaresupportedinallmodernbrowsers. asyncfunctionfuncName(url){ constresponse=awaitfetch(url); vardata=awaitresponse.json(); } Share Follow answeredMay9,2021at6:01 Azer8Azer8 39144silverbadges1717bronzebadges Addacomment  |  5 SETOFFUNCTIONSRECIPESEASYANDSIMPLE IpreparedasetoffunctionsthataresomehowsimilarbutyetdemonstratenewfunctionalityaswellasthesimplicitythatJavascripthasreachedifyouknowhowtotakeadvantageofit. Letsomebasicconstants letdata; constURLAPI="https://gorest.co.in/public/v1/users"; functionsetData(dt){ data=dt; } Mostsimple //MOSTSIMPLEONE functionmakeRequest1(){ fetch(URLAPI) .then(response=>response.json()).then(json=>setData(json)) .catch(error=>console.error(error)) .finally(()=>{ console.log("Datareceived1-->",data); data=null; }); } VariationsusingPromisesandAsyncfacilities //ASYNCFUNCTIONS functionmakeRequest2(){ fetch(URLAPI) .then(asyncresponse=>awaitresponse.json()).then(asyncjson=>awaitsetData(json)) .catch(error=>console.error(error)) .finally(()=>{ console.log("Datareceived2-->",data); data=null; }); } functionmakeRequest3(){ fetch(URLAPI) .then(asyncresponse=>awaitresponse.json()).then(json=>setData(json)) .catch(error=>console.error(error)) .finally(()=>{ console.log("Datareceived3-->",data); data=null; }); } //BetterPromiseusages functionmakeRequest4(){ constresponse=Promise.resolve(fetch(URLAPI).then(response=>response.json())).then(json=>setData(json)).finally(()=>{ console.log("Datareceived4-->",data); }) } Demostrationofonelinerfunction!!! //ONELINERSTRIKEASYNCWRAPPERFUNCTION asyncfunctionmakeRequest5(){ console.log("Datareceived5-->",awaitPromise.resolve(fetch(URLAPI).then(response=>response.json().then(json=>json)))); } WORTHMENTION--->@DanielDeLeónpropablythecleanestfunction* (async()=> console.log( (await(awaitfetch(URLAPI)).json()) ) )(); Thetopanswer->By@tggagneshowsfunctionalitywithHttpClientAPI. ThesamecanbeachievewithFetch.AsperthisUsingFetchbyMDNshowshowyoucanpassaINITassecondargument,basicallyopeningthepossibilitytoconfigureeasilyanAPIwithclassicmethods(get,post...). //ExamplePOSTmethodimplementation: asyncfunctionpostData(url='',data={}){ //Defaultoptionsaremarkedwith* constresponse=awaitfetch(url,{ method:'POST',//*GET,POST,PUT,DELETE,etc. mode:'cors',//no-cors,*cors,same-origin cache:'no-cache',//*default,no-cache,reload,force-cache,only-if-cached credentials:'same-origin',//include,*same-origin,omit headers:{ 'Content-Type':'application/json' //'Content-Type':'application/x-www-form-urlencoded', }, redirect:'follow',//manual,*follow,error 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 body:JSON.stringify(data)//bodydatatypemustmatch"Content-Type"header }); returnresponse.json();//parsesJSONresponseintonativeJavaScriptobjects } postData('https://example.com/answer',{answer:42}) .then(data=>{ console.log(data);//JSONdataparsedby`data.json()`call }); Node FetchisnotavailableonNode(ServerSide) Theeasiestsolution(endof2021)istouseAxios. $npminstallaxios ThenRun: constaxios=require('axios'); constrequest=async(url)=>await(awaitaxios.get(url)); letresponse=request(URL).then(resp=>console.log(resp.data)); Share Follow editedDec8,2021at19:03 answeredAug4,2021at17:39 FedericoBaùFedericoBaù 3,38833goldbadges1717silverbadges2626bronzebadges Addacomment  |  4 functionget(path){ varform=document.createElement("form"); form.setAttribute("method","get"); form.setAttribute("action",path); document.body.appendChild(form); form.submit(); } get('/my/url/') Samethingcanbedoneforpostrequestaswell. HavealookatthislinkJavaScriptpostrequestlikeaformsubmit Share Follow editedMay23,2017at11:47 CommunityBot 111silverbadge answeredJul3,2016at9:34 GauravGuptaGauravGupta 1,82944goldbadges2020silverbadges3737bronzebadges Addacomment  |  4 Torefreshbestanswerfromjoannwithpromisethisismycode: lethttpRequestAsync=(method,url)=>{ returnnewPromise(function(resolve,reject){ varxhr=newXMLHttpRequest(); xhr.open(method,url); xhr.onload=function(){ if(xhr.status==200){ resolve(xhr.responseText); } else{ reject(newError(xhr.responseText)); } }; xhr.send(); }); } Share Follow answeredJun27,2018at14:01 negsteknegstek 52866silverbadges2121bronzebadges Addacomment  |  4 Simpleasyncrequest: functionget(url,callback){ vargetRequest=newXMLHttpRequest(); getRequest.open("get",url,true); getRequest.addEventListener("readystatechange",function(){ if(getRequest.readyState===4&&getRequest.status===200){ callback(getRequest.responseText); } }); getRequest.send(); } Share Follow editedJan18,2019at18:40 answeredNov18,2018at16:56 user10167940user10167940 Addacomment  |  3 Ajax You'dbebestoffusingalibrarysuchasPrototypeorjQuery. Share Follow editedJan27,2014at13:52 PeterMortensen 29.8k2121goldbadges9898silverbadges124124bronzebadges answeredOct29,2008at16:33 GregGreg 305k5252goldbadges362362silverbadges328328bronzebadges 0 Addacomment  |  2 //CreatearequestvariableandassignanewXMLHttpRequestobjecttoit. varrequest=newXMLHttpRequest() //Openanewconnection,usingtheGETrequestontheURLendpoint request.open('GET','restUrl',true) request.onload=function(){ //BeginaccessingJSONdatahere } //Sendrequest request.send() Share Follow answeredSep5,2019at6:00 PradeepMauryaPradeepMaurya 33422silverbadges77bronzebadges Addacomment  |  2 InpurejavascriptandreturningaPromise: httpRequest=(url,method='GET')=>{ returnnewPromise((resolve,reject)=>{ constxhr=newXMLHttpRequest(); xhr.open(method,url); xhr.onload=()=>{ if(xhr.status===200){resolve(xhr.responseText);} else{reject(newError(xhr.responseText));} }; xhr.send(); }); } Share Follow answeredAug23,2021at17:56 tbo47tbo47 1,70311goldbadge1616silverbadges1010bronzebadges Addacomment  |  1 IfyouwanttousethecodeforaDashboardwidget,andyoudon'twanttoincludeaJavaScriptlibraryineverywidgetyoucreated,thenyoucanusetheobjectXMLHttpRequestthatSafarinativelysupports. AsreportedbyAndrewHedges,awidgetdoesn'thaveaccesstoanetwork,bydefault;youneedtochangethatsettingintheinfo.plistassociatedwiththewidget. Share Follow answeredAug7,2010at5:03 apadernoapaderno 26.4k1616goldbadges7474silverbadges8686bronzebadges Addacomment  |  0 YoucandoitwithpureJStoo: //CreatetheXHRobject. functioncreateCORSRequest(method,url){ varxhr=newXMLHttpRequest(); if("withCredentials"inxhr){ //XHRforChrome/Firefox/Opera/Safari. xhr.open(method,url,true); }elseif(typeofXDomainRequest!="undefined"){ //XDomainRequestforIE. xhr=newXDomainRequest(); xhr.open(method,url); }else{ //CORSnotsupported. xhr=null; } returnxhr; } //MaketheactualCORSrequest. functionmakeCorsRequest(){ //ThisisasampleserverthatsupportsCORS. varurl='http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html'; varxhr=createCORSRequest('GET',url); if(!xhr){ alert('CORSnotsupported'); return; } //Responsehandlers. xhr.onload=function(){ vartext=xhr.responseText; alert('ResponsefromCORSrequestto'+url+':'+text); }; xhr.onerror=function(){ alert('Woops,therewasanerrormakingtherequest.'); }; xhr.send(); } See:formoredetails:html5rockstutorial Share Follow editedNov21,2017at11:18 Kondal 2,61344goldbadges2323silverbadges3939bronzebadges answeredOct11,2016at16:02 jpereirajpereira 54866silverbadges1111bronzebadges Addacomment  |  0 Hereisanalternativetoxmlfilestoloadyourfilesasanobjectandaccesspropertiesasanobjectinaveryfastway. Attention,sothatjavascriptcanhimandtointerpretthecontentcorrectlyitisnecessarytosaveyourfilesinthesameformatasyourHTMLpage.IfyouuseUTF8saveyourfilesinUTF8,etc. XMLworksasatreeok?insteadofwriting value writeasimplefilelikethis: Property1:value Property2:value etc. Saveyourfile.. Nowcallthefunction.... varobjectfile={}; functiongetfilecontent(url){ varcli=newXMLHttpRequest(); cli.onload=function(){ if((this.status==200||this.status==0)&&this.responseText!=null){ varr=this.responseText; varb=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':''); if(b.length){ if(b=='\n'){varj=r.toString().replace(/\r/gi,'');}else{varj=r.toString().replace(/\n/gi,'');} r=j.split(b); r=r.filter(function(val){if(val==''||val==NaN||val==undefined||val==null){returnfalse;}returntrue;}); r=r.map(f=>f.trim()); } if(r.length>0){ for(vari=0;i1){ varmname=m[0]; varn=m.shift(); varivalue=m.join(':'); objectfile[mname]=ivalue; } } } } } cli.open("GET",url); cli.send(); } nowyoucangetyourvaluesefficiently. getfilecontent('mesite.com/mefile.txt'); window.onload=function(){ if(objectfile!==null){ alert(objectfile.property1.value); } } It'sjustasmallgifttocontibutetothegroup.Thanksofyourlike:) IfyouwanttotestthefunctiononyourPClocally,restartyourbrowserwiththefollowingcommand(supportedbyallbrowsersexceptsafari): yournavigator.exe''--allow-file-access-from-files Share Follow editedMar15,2019at10:52 answeredMar15,2019at10:34 CherifCherif 5322bronzebadges Addacomment  |  0 GETCONTENT Share Follow answeredSep6,2019at6:06 RamaRama 14722silverbadges44bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascripthttp-getdashcodeoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 4 ParseJSONfromURLwithJavascript 2 HowtoHTTPRequestaURLinJavaScript? 3 HowdoIassigntextfromfiletoavariablewithjavascript? 3 HowtogetsourcecodeofspecificURLinJavaScript? 2 Apage(p1)hasalinktoanotherpage(p2).IwanttoaccessthelinkspresentinP2fromP1 2 Executeapicallfromhtmlbutton...How 1 Parsejsondatainjavascriptonline -1 HowtomakeanHTTPrequestfromHTML? 0 GettingthesourcecodeanyURLwithJavaScript 0 Howtogetfiledatafromurlinjavascript Seemorelinkedquestions Related 2785 LengthofaJavaScriptobject 2502 ValidatedecimalnumbersinJavaScript-IsNumeric() 3098 Detectinganundefinedobjectproperty 5236 What'sthebestwaytovalidateanemailaddressinJavaScript? 7625 HowdoJavaScriptclosureswork? 1690 JavaScriptpostrequestlikeaformsubmit 4582 HowdoIcheckifanarrayincludesavalueinJavaScript? 2682 HTTPGETwithrequestbody 8137 Whatdoes"usestrict"doinJavaScript,andwhatisthereasoningbehindit? 2404 Generaterandomstring/charactersinJavaScript HotNetworkQuestions Inacyberpunkworldwherecorporateupperclasscitizenscanworkvirtuallythroughimplants,whywouldtheybuildcorporatemega-skyscrapers? Haskellcomparingtwolists'lengthsbutoneofthemisinfinite? Bookaboutamanwhoisturnedintoaquadrupedwhilesearchingforacolonyshiponanalienworld RecreateMinecraft'slighting Inthesentence"Thetablewassetforlunch"is"set"averboranadjective? Woulditbepossibleforoneairlinertotowanother? HowDoesOrbitalWarfareWork? ArrangeaHaft-Sintable Combineeachelementwithalltheothersinsublists Howdoeslicensingsoftwarenotimplyownership?Don'tIownaWindowsoperatingsystemonceIpayforit? TikZarcwithextremeangle ArticleorRelativePronoun Howcanfourbethehalfoffive? FrameStringsthatcontainnewlines Whentoconvertanordinalvariabletoabinaryvariable? My(manual)transmissionwon'tengageanygear1dayafterescapingbog NFA:Howdoesitfunctionwithempty-stringmoves? IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? Simplequadraticfunction,butcan'tunderstandthequestion WhatwastheethniccompositionofSovietgovernment? Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? HowDoesBlackWinThisposition Isthereamagneticfieldaroundafullychargedcapacitor? Whatpeople,ifany,pushedPutinintothewarwithUkraine? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-js Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?