Ajax and JSP mixed use

Source: Internet
Author: User

The first thing to know is that Ajax is a technique to update parts of a Web page without reloading the entire page.

What is AJAX?

AJAX = asynchronous JavaScript and XML.

AJAX is a technique for creating fast, Dynamic Web pages.

AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.

Traditional Web pages (without AJAX) if you need to update the content, you must reload the entire page surface.

How Ajax Works

Ajax requests

The AJAX request relies on the XMLHttpRequest object, so the object is created before the request

    var xmlhttp;    //兼容性写法创建请求实例,IE5 6支持else里面的方法if (window.XMLHttpRequest){            new XMLHttpRequest();        }else {            new ActiveXObject("Microsoft.XMLHTTP");        }

Then send the request to the server
The open function has three parameters, the request method, the request address, the request is asynchronous or synchronous
The Send (string) function has a parameter that requires a string parameter only if the request is in the form of a post.

So what's the difference between get and post?
GET is simpler and faster than POST, and can be used in most cases.

However, use the POST request in the following cases:

  • Unable to use cache file (update file or database on server)
  • Send a large amount of data to the server (POST has no data volume limit)
  • Post is more stable and more reliable than GET when sending user input with unknown characters
  • //设置传送方式,地址,以及同步还是异步        xmlhttp.open("GET","Test.jsp?value="+escape(value),true);         xmlhttp.onreadystatechange = callback;//状态改变的时候执行这个函数,用来判断是否请求完毕        xmlhttp.send();//请求服务器,如果使用post方式,则send里面要带上传递的参数        //post方式         /**         xmlhttp.open("POST","Test.jsp",true);         xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");         xmlhttp.send("value="+value);         */

    Then the server side processes and returns, this is placed in the instance has the specific code

    Set the return response in the callback function callback

    onReadyStateChange stores functions (or function names) and calls the function whenever the ReadyState property changes.
    ReadyState have XMLHttpRequest state. Vary from 0 to 4.

    0: Request not initialized
    1: Server Connection established
    2: Request received
    3: In Request processing
    4: The request is complete and the response is ready

    Status: "OK"
    404: Page Not Found

    The type of the appropriate server
    ResponseText gets the response data in the form of a string.
    Responsexml gets the response data in XML form. This is usually used when the URL in open is an XML file.

    function callback(){        //请求完成表示        if(xmlhttp.readyState ==4 && xmlhttp.status==200){            //设置相应操作            }        }    }

    In general, for these steps, here is the detailed code

    Instance

    First, create a text box to test the user name, and add the Listener event onblur, which means that when the focus is lost, it is executed and a span empty tag is created behind it to dynamically display the information, indicating whether the name is occupied

    <form Method="POST" action="ajax.jsp">        <table>            <tr>                <TD><input type="text" id="userid" onblur= "checkuser ()" ><span style="color:red" id="Spanid"></span></td>            </tr>        </table>    </form>

    Next is the JS code, using AJAX to send the input content to the server, the server to verify

    varxmlHTTP function checkuser(){        varValue = document.getElementById ("userid"). Value;//Compatibility notation Create request instance, IE5 6 support else inside method        if(Window. XMLHttpRequest) {xmlhttp =NewXMLHttpRequest (); }Else{xmlhttp =NewActiveXObject ("Microsoft.XMLHTTP"); }//Set transfer mode, address, and synchronous or asynchronousXmlhttp.open ("GET","Test.jsp?value="+Escape(value),true); Xmlhttp.onreadystatechange = callback;//The function is executed when the state is changed to determine if the request is completeXmlhttp.send ();//Request Server}

    Then the server side gets the data and writes back

    <%    response.setHeader("Cache-Control","no-store");//HTTP1.1    response.setHeader("Pragma","no-cache");//HTTP1.0    response.setDateHeader("Expires",0);//禁止在服务器中缓存    value = request.getParameter("value");//获取传送过来的参数    response.getWriter().write(value);//模拟数据写回%>

    The client then processes the data that the server writes back in the callback function

    /**     * 回调函数     */    function callback(){        //请求完成表示        if(xmlhttp.readyState ==4 && xmlhttp.status==200){            alert(xmlhttp.responseText);//相应返回的text//            alert(xmlhttp.responseXML);//相应返回的xml            if (xmlhttp.responseText){//这里直接判断不为空,应该根据数据库返回值来进行不同的显示                var spanid = document.getElementById("spanid");                "注册成功";            }        }    }

    The effect is when the input box loses focus immediately judgment, of course, the actual judgment is to connect to the database, in order to simply print out directly

    Ajax and JSP mixed use

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.