用Javascript向服务器发送数据

来源:互联网 发布:淘宝迪奥包包 编辑:程序博客网 时间:2024/05/27 20:56

第一种方式是,点击链接,触发一个js函数,在该函数内,用dom生成表单和输入框,将值赋在表单里,提交表单。

function postwith(to, p) {var myForm = document.createElement("form");myForm.method = "post";myForm.action = to;for ( var k in p) {var myInput = document.createElement("input");myInput.setAttribute("name", k);myInput.setAttribute("value", p[k]);myForm.appendChild(myInput);}document.body.appendChild(myForm);myForm.submit();document.body.removeChild(myForm);}
 <body>    <a href="javascript:postwith('save',{'currentPage':'2','xisuo':'计算机'})">use js to post</a>
save是个servlet

public class save extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String currentPage = request.getParameter("currentPage");String xisuo = request.getParameter("xisuo");System.out.println(currentPage+"---"+xisuo);response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.print("    This is ");out.print(this.getClass());out.println(", using the POST method1111111111");out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();}


第二种是用表单
<body>    <form name="form1" action="post-data-result.jsp" method="post"><input name="post_data" type="text"></input><input type="button" onclick="postData()" value="提交"></input></form><form name="form2" action="post-data-result.jsp" method="post"><input name="post_data" type="text"></input><input type="button" onclick="postData()" value="提交"></input></form><form name="form3" action="post-data-result.jsp" method="post"><input name="post_data" type="text"></input><input type="button" onclick="postData()" value="提交"></input></form>  </body>
function postData(){var myForm = document.createElement("form");myForm.method = "post";myForm.action = "post-data-result.jsp";var inputs=document.getElementsByName("post_data");var i;for (i=0;i<inputs.length;i++) {var myInput = document.createElement("input");myInput.type = "text";myInput.name="post_data";myInput.value=inputs[i].value;myForm.appendChild(myInput);}document.body.appendChild(myForm);myForm.submit();document.body.removeChild(myForm);}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>获得客户端数据</title></head><body><%//这里设置的字符集要跟index.html中的charset一致request.setCharacterEncoding("utf-8");String[] text=request.getParameterValues("post_data");for(String t : text){out.print(t+"<br>");}%></body></html>


原创粉丝点击