web数据的传输

来源:互联网 发布:电脑淘宝怎么看信用 编辑:程序博客网 时间:2024/06/05 16:17

数据的传输是web重要的部分。

1、表单

我们的数据一般是放在表单里,表单数据的提交方式有http协议的post和get方法。

方法一:表单数据的提交可以用submit方法实现:

<form action=’http://www.123.com/postValue’ method=’post’><input type=’text’ name=’username’ /><input type=’password’ name=’password’/><input type=’submit’ value=’登陆'/></form>




点击登录按钮就可以提交数据,但是这种提交方法返回的东西会导致页面重新加载。

这种默认的提交方式,一般会进行页面的跳转(不成功时跳转到当前页面)。而有时候我们是对弹出框进行数据提交的,希望提交成功则关闭弹出框并刷选父页面,失败则提示失败原因,且弹出框不关闭。此时可以采用Ajax进行数据提交。


方法二:使用button的方法提交

<input type="button" value="登 录" class="btn" onClick="userformSubmit();"/>

function userformSubmit(){var _params = {loginName:document.getElementById("userform").loginName.value,password:document.getElementById("userform").password.value};Ext.Ajax.request({url : serviceURL,success : function(response, options) {var result = {};try {result = Ext.decode(response.responseText);} catch (e) {}success(result, options);},failure : function(response, options) {var result = {};try {result = Ext.decode(response.responseText);} catch (e) {}failure(result, options);},params : _params});}

<input type="button" id="submitForm" value="登 录" class="btn" onClick="userformSubmit();"/>
function userformSubmit(){    document.getElementById("submitForm").submit();}


方法三:

使用Ajax提交表单数据

<script type="text/JavaScript" src="/js/jQuery/jquery.form.js"></script>   //ajaxForm 依赖脚本

<form name="testForm" id="testForm" ><input type="button" value="submit"/></form><script type="text/javascript">var options = {           target:        '#output1',   // target element(s) to be updated with server response           beforeSubmit:  showRequest,  // pre-submit callback           success:       showResponse  // post-submit callback             // other available options:           //url:       url         // override for form's 'action' attribute           //type:      type        // 'get' or 'post', override for form's 'method' attribute           //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)           //clearForm: true        // clear all form fields after successful submit           //resetForm: true        // reset the form after successful submit             // $.ajax options can be used here too, for example:           //timeout:   3000       };   $('#testForm').ajaxSubmit(options);}</script>

2、jsp内置对象

通过内置对象传送或者接收数据

session(一次对话):session.setAttrbute();session.getAttrbute();

request(一次请求):

getParameter 是用来接受用post个get方法传递过来的参数的.
getAttribute 必须先setAttribute.

request.setAttribute()和request.getAttrbute();

http的请求数据,使用request.getParameter()方法得到。没有setParameter方法。

一般通过表单和链接传递的参数使用getParameter
对于重定向(response.sendRedirect)request.setAttrbute()中的参数,将不会重定向到新的jsp。


pageContext:

pageContext.setAttribute();和pageContext.getAttribute();

作用域范围:对象的作用是取得任何范围的参数,在JSP页面中可以直接使用 pageContext对象


3、jsp获取servlet的数据

可以通过javabean的方法获取。在servlet中将值方法javaBean中,然后在jsp界面用<%%>或者<%=%>的方法得到数据。

Java代码中对页面的输出out.print();

<%
        String str = "JSP java代码输出测试!";
        //第一种输出方式
        out.print(str);
    %>
    <!-- 第二种输出方式-->
      <%=str%>


3、ajax

使用Ajax进行数据交互。

Ajax与普通的表单提交不太一样。一般表单的数据交互页面都会重新加载,而Ajax只是对改变的部分进行操作。

Ajax的常用写法:

var params = {};var success_callback = function(response) {}var failure_callback = function(xhr) {};var complete_callback = function(xhr) {}var options = {"url" : "","data" : params,"beforeSend" : function() {doMask("请稍等...");},"success" : success_callback,"error" : failure_callback,"complete" : complete_callback,"type" : "post"};$.ajax(options);

4、jGrid

请求与处理,数据表格

JQGrid是一个在jquery基础上做的一个表格控件,以ajax的方式和服务器端通信。

jqGrid是典型的B/S架构,服务器端只是提供数据管理,客户端只提供数据显示。换句话说,jqGrid可以以一种更加简单的方式来展现你数据库的信息,而且也可以把客户端数据传回给服务器端。 
对于jqGrid我们所关心的就是:必须有一段代码把一些页面信息保存到数据库中,而且也能够把响应信息返回给客户端。jqGrid是用ajax来实现对请求与响应的处理。


5、跨域数据传输

方法一:利用jsonp进行跨域

<script type="text/javascript"src="http://code.jquery.com/jquery-latest.js"></script>  <scripttype="text/javascript">     $.ajax({          url:"http://localhost:8080/MyTest?callback=?",            dataType:"jsonp",          jsonpCallback:"person",          success:function(data){              alert(data.name + " is aa" + data.sex);          }     });  </script>

方法二:利用iframe的get请求。

将数据提交到savaFrameiframe中去

<%         String path =request.getContextPath();         String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;         //获取服务器的协议端口,和项目名称 %><form name='resourceform' id='resourceform'action='跨域的url' method='post' enctype='multipart/form-data' class="searchbar"target="savaFrame">              <table class="table">                                   <thead>                                          <tr>                                                 <th colspan="2">                                                        选择并上传资源文件:                                                 </th>                                          </tr>                                   </thead>                                   <tbody>                                          <tr>                                                 <td align="right" width="20%">资源文件:</td>                                                 <td class="edit" width="80%"><input type='file' id="resource_file"name='resource_file' value='' class="ipt-2"/><span class="warning">* </span></td>                                          </tr>                                          <tr>                                                 <td align="right">资源名称:</td>                                                 <td class="edit"><input type="text"style="line-height: 23px;" name="resource_name"  value=""/>                                                                                                 </td>                                          </tr>                                          <tr>                                                 <td colspan="2" >                                                        <div style="text-align:center;width:100%;">                                                                                                               <input type="hidden" id="callack"name="backurl" value="<%=basePath+"/deal_callback.jsp" %>"></input>                                                                                                                                                                <button type="button" onclick="formSubmit();"class="btn btn-blue">确定上传</button>                                                        </div>                                                 </td>                                          </tr>                                   </tbody>                            </table></form><!-- /*隐藏的iframe*/ -->      <div style="display:none"><iframe id="savaFrame"name="savaFrame" style="width:0px;height:0px;" src=""></iframe>     </div>      /*回调函数的编写*/   <script> function jsonp(data){         //        alert("回调函数")            var status = data['status'];            var code = data['code'];            alert(JSON.stringify(data));            if(status == '1'){                alert("上传成功");                goBack();            }else{                alert("上传失败");                //doRefreshPage();            }                }   </script>


deal_callback.jsp
<%@ pagelanguage="java" import="java.util.*"pageEncoding="utf-8"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>    <head>      <base href="<%=basePath%>">           <meta http-equiv="pragma" content="no-cache">     <meta http-equiv="cache-control"content="no-cache">     <meta http-equiv="expires"content="0">        <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">     <meta http-equiv="description"content="This is my page">    </head>     <body><br>    </body>     <script type="text/javascript">    var rs =window.location.search.split('?').slice(1);    rs =rs.toString().split('&');    var data = {};    for(var i in rs){        var map = rs[i].split("=");        data[map[0]]= map[1];    }    window.parent.jsonp(data);  </script>  </html>


参考原文:

1、http://www.cnblogs.com/leirenyuan/p/6016063.html(jsp 九大内置对象和其作用详解)

2、http://www.cnblogs.com/CodeGuy/archive/2012/02/13/2349970.html(转发与重定向)

3、http://blog.csdn.net/jgwei/article/details/84475693(JGrid学习)

4、http://blog.csdn.net/w329636271/article/details/44773349(跨域数据传输)


0 0