zoukankan      html  css  js  c++  java
  • 重点+超详细:ajax和json及案例

    不用jQuery的ajax流程

    <!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>Insert title here</title>
    </head>
    <script>
    /*
     * 1.大致的流程
     *    * 创建核心对象
     *    * 绑定一个函数
     *    * 打开和服务端连接
     *    * 发送数据
     *    * 处理函数   成本的付出
     * 2.核心对象的5种状态分别代表的含义
     */    
    function GetXmlHttpObject()
    {
      var xmlHttp=null;
      try
        {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        }
      catch (e)
        {
        // Internet Explorer
        try
          {
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        }
      return xmlHttp;
    }
    function fn(){
        //1.创建对象
        var xmlHttpRequest=GetXmlHttpObject();
        //2.绑定函数
        xmlHttpRequest.onreadystatechange=fm;
        //3.打开
        xmlHttpRequest.open("get","test.jsp",true);
        //4.发送
        xmlHttpRequest.send();
        //5.处理绑定函数
        function fm(){
            if (xmlHttpRequest.readyState==4)
            {
              if (xmlHttpRequest.status==200)
              {
                document.getElementById('dv').innerHTML=xmlHttpRequest.responseText;
              }
              else
              {
                alert("Problem retrieving data:" + xmlHttpRequest.statusText);
               }
            }
        }
        
    }
    </script>
    <body>
    <button onclick="fn()">按钮</button>
    <div id="dv"></div>
    </body>
    </html>

    test.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <%
        out.println("AAAAAA");
    %>

    基于jQuery的ajax

    xml格式的数据

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <!--   引入jQuery -->
    <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></script>
    <script language="javascript" >
    $(function(){
        $("#send").click(function(){
          //获取id是username和content的值,回调函数dt的值是返回的数据 $.post(
    "demo2.jsp",{"username":$("#username").val(),"content":$("#content").val()},function(dt){ //alert(dt); //保证第一行的XML数据没有空行 var um=$(dt).find("comments comment").attr("username"); var con=$(dt).find("comments content").text(); $("#resText").html(um+" "+con); },"xml"); }); }); </script> </head> <body> <form id="form1"> <p>评论:</p> <p>姓名: <input type="text" name="username" id="username" /></p> <p>内容: <textarea name="content" id="content" ></textarea></p> <p><input type="button" id="send" value="提交"/></p> </form> <div class='comment'>已有评论:</div> <div id="resText" > </div> </body> </html>

    demo2.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
    //注意空行问题
      String username = request.getParameter("username");
      String content = request.getParameter("content");
      response.setContentType("text/xml");
      out.println("<?xml version='1.0' encoding='UTF-8'?>");
      out.println("<comments>");
      out.println("<comment username='"+username+"'>");
      out.println("<content>"+content+"</content>");
      out.println("</comment>");
      out.println("</comments>");
    %>

    json格式的数据

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <!--   引入jQuery -->
    <script src="../../jquery-1.4.2.js" type="text/javascript"></script>
    <script language="javascript" >
    $(function(){
        $("#send").click(function(){
            //$.post("demo3.jsp",{"username":$("#username").val(),"content":$("#content").val()},function(dt){
              // 将JSON格式的字符串转换为JS对象
              // var dd=eval("("+dt+")")
              // alert(dd.username);    
               //alert(dd.content);    
            //});
            
            
            $.post("demo3.jsp",{"username":$("#username").val(),"content":$("#content").val()},function(dt){
               
               alert(dt); 
               $("#resText").html(dt.username+" "+dt.content);    
            },"json");
        });
    });    
    
    
    </script>
    </head>
    <body>
    <form id="form1">
    <p>评论:</p>
     <p>姓名: <input type="text" name="username" id="username" /></p>
     <p>内容: <textarea name="content" id="content" ></textarea></p>
     <p><input type="button" id="send" value="提交"/></p>
    </form>
    <div id="resText" >
    </div>
    </body>
    </html>

    demo3.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
      String username = request.getParameter("username");
      String content = request.getParameter("content");
      System.out.print("{"username":""+username+"","content":""+content+""}");
      out.print("{"username":""+username+"","content":""+content+""}");
    %>

    这是我之前项目中总用到的类型,重点:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <!--   引入jQuery -->
    <script src="../../jquery-1.4.2.js" type="text/javascript"></script>
    <script language="javascript" >
        $(function(){
            /*
             * $.ajax({url:'',data:{},type:'',dataType:'json',success:function(dt){},error:function(){}});
             */
            $("#send").click(function(){
                //$.ajax(); ==> $.ajax({});  ===>$.ajax({k1:v1,k2:v2,k3:v3.....});
                $.ajax({
                    //请求的路径
                    url:'demo.jsp',
                    //发送到服务端的数据
                    data:{username:$("#username").val(),content:$("#content").val()},
                    //请求的类型
                    type:'post',
                    //响应回的数据 格式
                    dataType:'json',
                    //成功之后处理的函数
                    success:function(dt){
                        //alert(dt);
                        $("#resText").html(dt.username+" "+dt.content);
                    },
                    //失败之后处理的函数
                    error:function(){
                        alert("Fail");
                    }
                });
            });
        })
    </script>
    </head>
    <body>
    <form id="form1">
    <p>评论:</p>
     <p>姓名: <input type="text" name="username" id="username" /></p>
     <p>内容: <textarea name="content" id="content" ></textarea></p>
     <p><input type="button" id="send" value="提交"/></p>
    </form>
    <div  class='comment'>已有评论:</div>
    <div id="resText" >
    </div>
    </body>
    </html>

    demo.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%
      String username = request.getParameter("username");
      String content = request.getParameter("content");
      out.print("{"username":""+username+"","content":""+content+""}");
    %>
  • 相关阅读:
    Nginx应用详解及配置
    mongodb复制+分片集原理
    memcached架构及缓存策略
    redis数据类型
    redis数据库安装 redis持久化及主从复制
    shell脚本-正则、grep、sed、awk
    kvm虚拟机管理基础
    kvm热添加和热迁移
    zabbix调用api检索方法
    kubernetes deployment升级和回滚
  • 原文地址:https://www.cnblogs.com/MessiAndDream/p/6096274.html
Copyright © 2011-2022 走看看