javascript - Send a string through an http request -


i starting learn how use xmlhttprequest , started this example w3schools want modify in order send string. new code:

<!doctype html> <html> <head> <script> function loadxmldoc() {     var xmlhttp;     var str="sent string";     xmlhttp=new xmlhttprequest();     xmlhttp.open("get","ajax_info.txt",true);     xmlhttp.send(str);     alert(xmlhttp.responsetext); } </script> </head> <body> <div id="mydiv"><h2>let ajax change text</h2></div> <button type="button" onclick="loadxmldoc()">change content</button> </body> </html> 

i want output response , see if string sent alert returns nothing. empty window. doing wrong?

also, found example in question adds these lines of code:

http.setrequestheader("content-type", "application/x-www-form-urlencoded"); http.setrequestheader("content-length", params.length); http.setrequestheader("connection", "close"); 

are necessary? if yes, why? code page sends string code doesn't work me either.

edit: updated code, still doesn't work. tried without sending string still nothing happens. not trying anymore in w3wschools, instead in right place, not have code in function anymore , made changes @quentin told me about:

<script> var xmlhttp=null; var str="sent_string"; xmlhttp=new xmlhttprequest(); xmlhttp.open("post","http://192.168.1.3:80",true); xmlhttp.setrequestheader("content-type", "text/plain"); xmlhttp.setrequestheader("content-length", str.length); xmlhttp.setrequestheader("connection", "close"); xmlhttp.send(str); xmlhttp.addeventlistener('load', function () {          alert(this.responsetext);      alert(xmlhttp.readystate);} ); </script> 

first, aren't waiting http response before try alert value.

alert(xmlhttp.responsetext); 

should be:

xmlhttp.addeventlistener('load', function () {     alert(this.responsetext); }); 

second, making request message body. need post (or put) request if want send request body:

xmlhttp.open("post","ajax_info.txt",true); 

third, sending plain text request telling server form encoded.

http.setrequestheader("content-type", "application/x-www-form-urlencoded"); 

should be

xmlhttp.setrequestheader("content-type", "text/plain"); 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -