[原生JS][POST]请求和响应(一)

虽然效率有点低,但是作为初学者,可以先看看这个,然后再去看后面用Json处理。

XMLHttpRequest介绍

XMLHttpRequest 对象用于在后台与服务器交换数据。

特点

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据

XMLHttpRequest使用

创建 XMLHttpRequest 对象

xmlhttp=new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

建立连接

xmlhttp.open(提交方式,目标页面,是否为异步方式,[可选参数]用户名,[可选参数]密码)
xmlhttp.open(method, url, async, username, password);
xmlhttp.open("post","/Login",true)

第一个参数[method]:HTTP 请求方法,必须参数,值包括 POSTGET HEAD,大小写不敏感。

第二个参数[url]:请求的 URL 字符串,必须参数,大部分浏览器仅支持同源请求。

第三个参数[async]:指定请求是否为异步方式,默认为 true。如果为 false,当状态改变时会立即调用 onreadystatechange 属性指定的回调函数。

第四个参数[username]:可选参数,如果服务器需要验证,该参数指定用户名,如果未指定,当服务器需要验证时,会弹出验证窗口。

第五个参数[password]:可选参数,验证信息中的密码部分,如果用户名为空,则该值将被忽略。

设置请求头

xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

POST 必须设置

发送请求(Post)

let name = document.forms['LoginForm']['username'].value;
let pwd = document.forms['LoginForm']['userpwd'].value;
let params="username="+encodeURIComponent(name)+"&userpwd="+encodeURIComponent(pwd);
xmlhttp.send(params);

1.你也可以不使用let,而是使用var

2.使用encodeURIComponent()避免在传参过程中出现中文乱码问题

3.如果使用get方式,则参数写在url里,然后xmlhttp.send(null)

例子

<input name="submit" type="button" id="submit" value="向服务器发出请求" />
<script>
window.onload = function () { //页面初始化
var b = document.getElementsByTagName("input")[0];
b.onclick = function () {
var url = "server.php?callback=functionName"; //设置查询字符串
var xhr = createXHR(); //实例化XMLHttpRequest 对象
xhr.open("GET", url, false); //建立连接,要求同步响应
xhr.send(null); //发送请求
console.log(xhr.responseText); //接收数据
}
}
</script>

响应

xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState===4) alert(xmlhttp.responseText);
}

当状态码改变时执行

如果.readyState等于4

则弹出窗口,显示内容为响应文本

Servlet

  	request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("username");
String pwd = request.getParameter("userpwd");
response.getWriter().write(Duser.userLoginCheck(name,pwd)+"");

response.getWriter().write() 的文本,在js里面使用xmlhttp.responseText接收

萌狼蓝天写的一个例子

前端

<!--Form-->
<form name="LoginForm" class="box_info" id="LoginForm" method="post" enctype="application/x-www-form-urlencoded" action="${pageContext.request.contextPath}/Login">
<!--Profile-->
<div class="box_profile">
<img src="res/img/pic.jpg" class="set_profile" alt="Profile"/>
</div> <div class="box_name">
<label for="username">User Email </label>&nbsp;&nbsp;|&nbsp;&nbsp;<span class="wrong1"></span><br/>
<input type="text" name="username" id="username">
</div> <div class="box_pwd">
<label for="userpwd">Password </label>&nbsp;&nbsp;|&nbsp;&nbsp;<span class="wrong2"></span><br/>
<input type="password" name="userpwd" id="userpwd">
</div> <div class="box_btn">
<!-- <button id="btn_login" onclick="formCheck()" >Login</button>-->
<input type="button" id="btn_login" onclick="formCheck()" value="Login" />
</div>
<div class="box_other">
<span class="register">
<a href="register.jsp">Register</a>
</span>
<span class="forget">
<a href="#">Forget Password</a>
</span>
</div>
<br/>
<div align="center">
<div style="display:inline-block;margin:10px;width: 10px;height: 10px;background: #0981f6" onclick="colorSet_Blue()"></div>
<div style="display:inline-block;margin:10px;width: 10px;height: 10px;background: #d9212b" onclick="colorSet_Red()"></div>
<div style="display:inline-block;margin:10px;width: 10px;height: 10px;background:#23A393" onclick="colorSet_Green()"></div>
</div>
</form>

关于这个前端样式,如果你喜欢的话可以访问下面这篇博客了解,然后进入gitee下载

【Web前端】【开源分享】H5登陆界面 - 2021年12月24日

JS

// 登陆用
function formCheck()
{
let name = document.forms['LoginForm']['username'].value;
let pwd = document.forms['LoginForm']['userpwd'].value;
let params="username="+encodeURIComponent(name)+"&userpwd="+encodeURIComponent(pwd);
if(name==null || name ===""){
document.getElementsByClassName('wrong1')[0].innerHTML="请输入用户名";
}else{
document.getElementsByClassName('wrong1')[0].innerHTML="";
if(pwd==null || pwd ===""){
document.getElementsByClassName('wrong2')[0].innerHTML="请输入密码";
}else{
document.getElementsByClassName('wrong2')[0].innerHTML="";
//提交数据
var myrequest = new XMLHttpRequest();
myrequest.open("post","/Login",true) myrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
myrequest.send(params); myrequest.onreadystatechange = function () {
if(myrequest.readyState===4) alert(myrequest.responseText);
}
}
}
}

Servlet

@WebServlet(name = "Login", value = "/Login")
public class Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("VCVxWorks");
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("username");
String pwd = request.getParameter("userpwd");
response.getWriter().write(Duser.userLoginCheck(name,pwd)+""); }
}

存在的问题

响应太慢了,前台等很久才显示结果,老师建议我使用Json进行数据传输。

引用资料

C语言中文网 - JS XMLHttpRequest入门教程

w3school - AJAX - 服务器响应

w3school - XML DOM - XMLHttpRequest 对象

【Javaweb】【Js】【Servlet】Js与Servlet交互 - Js请求Servlet与响应Servlet的更多相关文章

  1. 利用servlet做转发,实现js跨域解决同源问题

    做前端开发,避免不了跨域这个问题,跨域具体什么概念,不赘述,博客里太多.简单说下,我们用js发请求,不管post还是get,如果发请求的对象和当前web页面不在同一域名下,浏览器的同源策略会限制发请求 ...

  2. JavaWeb学习总结-05 Servlet 与页面的交互(02)

    一 模拟请求数据 为了测试方便,把请求 json,txt, xml,html格式的文件放到了公网上面,可以通过以下地址请求: http://wx.glab.cn/xpxiaowu4java/json/ ...

  3. js(javascript)与OC(Objective-C)交互

    实质上oc与js的通信交互就是发送消息,也即函数调用,iOS7以后官方公布JavaScriptCore framework中很方便我们对他们之间的相互调用.在以前我们只能通过UIWebView的UIW ...

  4. 转载:js和as间的交互

    转载一: 提及AS3与外部脚本的交互,笔者认为可以总结成两种.一是AS3调用外部函数,二是外部脚本调用AS3函数.无外乎就 这两种.在调用函数的同时,我们还可以向函数传递一些参数.这就达到了传递数据的 ...

  5. 表单验证--通过原生js模仿ajax的异步交互

    今天给大家带来个福利,我也是刚刚学习的很实用的一个东西,通过原生js模仿ajax的异步交互. 我的博客只是给那些新手看的大神勿喷,写的不好可留言,请指出. 因为当初自己学的时候一个问题不会找人问,知道 ...

  6. js和android及ios交互

    Android中Java和JavaScript交互 这种交互,Hybrid App 会用的比较多一点, 本文将介绍如何实现Java代码和Javascript代码的相互调用. Android提供了一个很 ...

  7. Node.js SDK与fabric链码交互开发

    1.本篇背景 前面已经对链码开发作了比较详细的介绍,并且对官方提供的 fabcar 链码进行了解读,本篇将介绍如何使用 Node.js SDK 与区块链网络中的链码进行交互. 本篇内容基本来自官方 H ...

  8. iOS JS 和 OC交互 / JS 和 native 相互调用

    现在app 上越来越多需求是通过UIWebView 来展示html 或者 html5的内容, js 和 native OC代码交互 就非常常见了. js 调用 native  OC代码 第一种机制 ( ...

  9. JS在与lua的交互心得

    最近在写一个项目,前端技术使用的是Vue,在与lua的交互过程,是通过一个公共JS,前端调用公共js的方法给lua发送命令,lua接到命令,去执行一些方法,然后又通过回调返回到了前端,由于是第一次写这 ...

  10. C#在WinForm中使用WebKit传递js对象实现与网页交互的方法

    这篇文章主要介绍了C#在WinForm中使用WebKit传递js对象实现与网页交互的方法,涉及针对WebBroswer控件及WebKit控件的相关使用技巧,需要的朋友可以参考下 本文实例讲述了C#在W ...

随机推荐

  1. iOS文本字数动态展示使用小结

    项目开发中经常用到类似这样的功能,文本输入的时候需要动态的显示文本输入字数.这里以多行文本框为例,介绍一下实现方案.核心代码如下 -(void)textViewDidChange:(UITextVie ...

  2. Cookie、sessionStorage、localStorage的区别 ?

    共同点:都是保存在浏览器端的. 区别: 1.cookie数据始终携带在同源的http请求中,即cookie在浏览器和服务器间来回传递,而sessionStorage和Localstorage不会自动把 ...

  3. 云原生周刊:优化 Uber 的持续部署丨2024.10.14

    开源项目推荐 Cog Cog 是将机器学习模型打包到容器的工具.可通过配置将机器学习模型所需的环境和依赖,自动打包到容器里方便部署,让你不再为编写 Docker 文件和 CUDA 而痛苦,还能自动启动 ...

  4. 使用 Prometheus 在 KubeSphere 上监控 KubeEdge 边缘节点(Jetson) CPU、GPU 状态

    作者:朱亚光,之江实验室工程师,云原生/开源爱好者. KubeSphere 边缘节点的可观测性 在边缘计算场景下,KubeSphere 基于 KubeEdge 实现应用与工作负载在云端与边缘节点的统一 ...

  5. KubeSphere 社区双周报 | OpenFunction 发布 v1.1.1 | 2023.6.9-6.22

    KubeSphere 社区双周报主要整理展示新增的贡献者名单和证书.新增的讲师证书以及两周内提交过 commit 的贡献者,并对近期重要的 PR 进行解析,同时还包含了线上/线下活动和布道推广等一系列 ...

  6. Fluent Operator v2.0 发布:Fluent Bit 新的部署方式——Fluent Bit Collector

    2019 年 1 月 21 日,KubeSphere 社区为了满足以云原生的方式管理 Fluent Bit 的需求开发了 FluentBit Operator.此后产品不断迭代,在 2021 年 8 ...

  7. 《大话设计模式》java实现:第一章-简单工厂模式

    在<大话设计模式>中,示例代码使用C#实现,所以我这里使用Java实现一遍书中的设计模式. 第一章是使用简单工厂实现计算器. 遇到了一个问题:在Operation父类中,我们可以定义两个操 ...

  8. Marklogic学习 系列专栏整理

    Marklogic学习 系列专栏整理 本人就是个松鼠怪,见到好东西都想收藏,在CSDN发现了这位博主写的一系列MarkLogic相关专栏觉得不错,今天已经看到第六个了,反正很好吃,趁着最近项目使用Ma ...

  9. DHorse v1.6.0 发布,基于 k8s 的发布平台

    版本说明 新增特性 支持Codeup(阿里云云效)代码仓库: 支持环境的自动部署: 优化特性 管理员角色部署环境部需要审批: 优化页面展示: 升级指南 升级指南 DHorse介绍 DHorse是一个轻 ...

  10. 2个月搞定计算机二级C语言——真题(7)解析

    1. 前言 本篇我们讲解2个月搞定计算机二级C语言--真题7 2. 程序填空题 2.1 题目要求 2.2 提供的代码 #include <stdio.h> int fun(char* s, ...