html页面的数据利用js或者Ajax传输到后台java、php

网页制作工程中会经常遇见数据的传输。然而对于java或者php等是在服务器执行的程序,当页面加载之后嵌在html的这些代码是最先执行的。所以利用简单的传递数据是有问题的。现在介绍几种不同的传递参数问题。

1、利用JS传递

            这里利用表单的post,在表单里面加一个隐藏表单元素比如: 

只需要把值传给value就,接下来就简单了。

2、主要写一下怎么用Ajax传数据到java服务器(对于php也是灵活改动即可)

Ajax可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。Ajax的功能很强大,值得去研究。

   直接代码解释吧

html页面代码。index.jsp

<%@ page import="java.sql.*"%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" %>


   
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>





AJAX calls using Jquery in Servlet


      
        
        




AJAX Demo using Jquery in JSP and Servlet

Enter your Name:



这是Ajax核心代码,代码很简单,稍微一看就会明白:


      

这是主要的代码片段。代码很简单,很容易看懂,是通过get的方法直接传入到后台java。

命名:ActionServlet.java

package ajaxdemo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ActionServlet
 */

public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public ActionServlet() {
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    	String name=null;
    	name = "Hello "+request.getParameter("user");
    	if(request.getParameter("user").toString().equals("")){
    		name="Hello User";
    	}
    	
    	
    	response.setContentType("text/plain");  
    	response.setCharacterEncoding("UTF-8"); 
    	response.getWriter().write(name); 
  
    	//System.out.println(name);
    }

  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
 			throws ServletException, IOException {
    	// TODO Auto-generated method stub
  
    }
    
}

对于jsp需要更改一下web.xml。在web-app标签里面加入下面代码,注意路径的准确性


    ActionServlet
    ajaxdemo.ActionServlet
   
   
    ActionServlet
    /ActionServlet/*
   


转载:(有改动)

http://www.programming-free.com/2012/08/ajax-with-jsp-and-servlet-using-jquery.html


你可能感兴趣的:(杂文)