AJAX基本用法
在工作中和一些大項(xiàng)目制作的時(shí)候,許多人都會(huì)選擇使用前后端分離技術(shù)即AJAX進(jìn)行項(xiàng)目的制作,使用AJAX不僅能提高效率而且更容易修改,使我們制作項(xiàng)目的時(shí)候更加的得心應(yīng)手。
在此給大家講解一下AJAX的用法,一共有五個(gè)核心內(nèi)容,掌握了這五個(gè)方面就掌握了AJAX技術(shù)的使用。
AJAX五個(gè)核心屬性分別是url, type, data, dataType, success這五個(gè)方面.
@1: url 目標(biāo)地址(對(duì)應(yīng)后臺(tái)的Servlet地址)
@2: type 使用方法的類型(post和get兩種)
@3: data 內(nèi)容(向目標(biāo)地址發(fā)送的內(nèi)容)
@4: dataType 文本類型(一般使用text和json)
@5: success 成功之后的操作
解釋說明:get和post在形式上和性能上的差異
? post傳輸數(shù)據(jù)時(shí),不需要在URL中顯示出來,而get方法要在URL中顯示。
? post傳輸?shù)臄?shù)據(jù)量大,可以達(dá)到2M,而get方法由于受到URL長(zhǎng)度的限制,只能傳遞大約1024字節(jié).
? post是為了將數(shù)據(jù)傳送到服務(wù)器段,get是為了從服務(wù)器段取得數(shù)據(jù)。當(dāng)然get之所以也能傳送數(shù)據(jù),只是用來設(shè)計(jì)告訴服務(wù)器,你到底需要什么樣的數(shù)據(jù),post的信息作為http請(qǐng)求的內(nèi)容,而get是在Http頭部傳輸?shù)摹?/p>
下面詳細(xì)講解一下用法
先看一下總體結(jié)構(gòu)
$.ajax({url:"http://localhost:8080/Ajax/login",type:"post",data:{name:name,pwd:pwd},dataType:"text",success:function(data){alert(data);}});分步詳解
看了上述五個(gè)核心屬性你還可以了解一下如下AJAX小案例,幫助你更快更好運(yùn)用。
AJAX參考小案例
沒有輸入任何內(nèi)容時(shí)
都輸入內(nèi)容時(shí)
前端代碼展示
后臺(tái)代碼展示
package servlet;import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String name = request.getParameter("name");String pwd = request.getParameter("pwd");response.setContentType("text/html");//解決跨域問題response.setHeader("Access-Control-Allow-Origin", "*");PrintWriter out = response.getWriter();System.out.println(request.getRemoteAddr()+"/"+name+":"+pwd);if(name != null && pwd != null && !"".equals(name) && !"".equals(pwd)){out.print("ok");}else{out.print("error");}out.flush();out.close();}}看到這里相信你已經(jīng)會(huì)簡(jiǎn)單使用了,了解更多關(guān)注我呦!!!
總結(jié)
- 上一篇: linux系统时间代表,Linux上有两
- 下一篇: ssms没有弹出服务器验证_powerb