【03】AJAX发送get请求
AJAX发送get请求一、发送GET请求二、设置请求参数一、发送GET请求1.创建html文件test.html中的内容!DOCTYPEhtmlhtmllangenheadmetacharsetUTF-8/metanameviewportcontentwidthdevice-width, initial-scale1.0/titleDocument/title/headbodybuttonidbtn点击发送请求/buttondividdd/divscriptletbtndocument.getElementById(btn);letdddocument.getElementById(dd);//为按钮btn绑定单击事件btn.onclickfunction(){// 1.创建对象constxhrnewXMLHttpRequest();//const设置常量// 2.初始化设置请求方法get和urlhttp://127.0.0.1:8000xhr.open(GET,http://127.0.0.1:8000);// 3.发送xhr.send();// 4.事件绑定处理服务端返回的结果/*onreadystatechange注解 on当……时候 readystate是xhr对象中的属性表示状态0 1 2 3 4 0.未初始化 1.open方法调用完毕 2.send方法调用完毕 3.服务端返回部分结果 4.服务端返回的所有结果 change改变*/xhr.onreadystatechangefunction(){// 判断服务器返回的所有结果if(xhr.readyState4){// 判断响应状态码200 401 403 500// 2xx 表示成功所以status的范围是[200300if(xhr.status200xhr.status300){console.log(xhr.status);//状态码console.log(xhr.statusText);//状态字符串console.log(xhr.getAllResponseHeaders());//响应头console.log(xhr.response);//响应体dd.innerHTMLxhr.response;//将响应体中的内容添加到文本框dd中}}};};/script/body/htmltest.js中的内容constexpressrequire(express);constappexpress();app.get(/,(request,response){response.setHeader(Access-Control-Allow-Origin,*);response.send(HELLO EXPRESS);});app.listen(8000,(){console.log(服务启动,800端口监听中……);});2.查看浏览器的显示结果二、设置请求参数1.test.html中的内容!DOCTYPEhtmlhtmllangenheadmetacharsetUTF-8/metanameviewportcontentwidthdevice-width, initial-scale1.0/titleDocument/title/headbodybuttonidbtn点击发送请求/buttondividdd/divscriptletbtndocument.getElementById(btn);letdddocument.getElementById(dd);btn.onclickfunction(){constxhrnewXMLHttpRequest();// 设置请求参数abcxhr.open(GET,http://127.0.0.1:8000?a100b200c300);xhr.send();xhr.onreadystatechangefunction(){if(xhr.readyState4){if(xhr.status200xhr.status300){dd.innerHTMLxhr.response;//将响应体中的内容添加到文本框dd中}}};};/script/body/htmltest.js中的内容和上面相同。2.查看浏览器的显示结果
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2415996.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!