Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
ajax 是前后端交互的重要手段或橋梁。它不是一個技術,是一組技術的組合。
ajax :a:異步;j:js;a:和;x:服務端的數據。
ajax的組成:
通過后臺與服務器進行少量數據交換,ajax可以使網頁實現異步更新。也就是在不需要重新加載整個網頁的情況下,能夠更新部分網頁的技術。傳統的網頁不使用ajax,如果需要更新內容,必須重新加載整個頁面。
ajax請求原理:創建一個網絡請求對象 -> 發送連接請求 -> 發送請求數據 -> 檢查網絡請求對象的狀態 -> 如果響應成功了 -> 瀏覽器接收返回數據并更新網頁。接下來詳細介紹對象的創建以及它的方法。
XMLHttpRequest 對象,用于后臺與服務器之間的數據交換,意味著可以在不加載整個網頁的情況下,更新部分內容或數據。現代瀏覽器基本都支持,但是低版本的IE不支持,如果我們考慮IE兼容問題創建對象的時候需要兼容創建。
考慮兼容時創建的對象:
var xhr ;
if( window.XMLHttpRequest ){ //檢查瀏覽器是否支持XMLHttpRequest
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP") //兼容IE6 IE5
}
3.1、open( )
設置請求的類型、請求接口、是否異步處理。
使用語法:open( method , url , async )
3.2、send( )
將請求發送到服務器。
使用語法:send( string )
使用發送方式不同的時候,傳輸數據添加方式也不同,所以我們介紹下分別為post和get時,數據是如何發送的?
3.3、提交方式
get發送請求時,需要傳給后臺的數據通過url來傳遞,多個參數之間使用 & 符號連接,使用時如下:
xhr.opn( "GET" , "1.php?name=hello&age=world" , true )
xhr.send()
使用 post 方式發送請求時,使用send來發送數據,有時需要設置數據格式,類似表單那樣,此時可通過 setRequestHeader 設置發送的數據格式
xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded")
Content-type常見類型:
readyState 存有 XMLHttpRequest 的狀態,它的值從 0-4 發生變化,分別代表的意義:
每當 readyState 狀態值發生改變時會,就會觸發 onreadystatechange 事件,對應著每個狀態值就會被觸發五次。當狀態值為 4 時表示網絡請求響應完畢,就可以獲取返回的值。
xhr.onreadystateChange = function(){
if( xhr.readyState==4 ){
if( xhr.status>=200 && xhr.status<300 || xhr.status==304 ){
console.log("請求成功",xhr.responseXML)
}else{
console.log("請求失敗")
}
}
}
通常我們需要獲取服務器返回的信息,然后對我們的網頁做相對應的結果展示,通常使用 XMLHttpRequest 的 responseText 或 responseXML 屬性。
responseText ---> 獲取到的是字符串形式。接收到可直接使用,無需轉換。
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
responseXML ---> 獲取到 XML 形式的數據。使用時需要解析,如:
<person>
<name>小米粒</name>
<age>18</age>
</person>
解析時:
document.getElementsByTagName("name")[0]
responseXML 目前已被 json 取代,所以作為了解就好。
var xhr ;
if( window.XMLHttpRequest ){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP") //兼容IE6 IE5
}
xhr.open('GET','1.txt',true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
console.log("請求成功",xhr.response) // 請求成功 abc
}else{
console.log("請求失敗")
}
}
}
1.txt 文檔內容為 abc。所以返回的結果也是abc
hinkPHP6獲取參數的方法有多種,初學者可能知道其中的一種,然后在看到其他人代碼的時候又換了個寫法,可能會一臉懵逼,下面就給大家總結一下ThinkPHP6中獲取參數的方法。
假設我們有以下4種請求URL:
① http://localhost/index/index/user/id/1.html
② http://localhost/index/index/user?id=1
③ http://localhost/index/index/user?name=admin
④ http://localhost/index/index/user?name=111admin222
var_dump(input('id')); // ①、②鏈接都是1,③、④都是NULL
$this->request->param(); // 該方法返回所有的參數,返回值是一個數組
$this->request->param('id'); // 獲取指定參數的值
$this->request->get('id'); // 只對②鏈接生效,獲取id的值
$this->request->param('id', 1, 'intval'); // 接收參數id的值并轉成整型,結果為1
注意:使用該方法之前需要先引入:use think\facade\Request;
Request::param(); // 獲取當前請求的所有變量
Request::param('name'); // 獲取請求的name值,返回字符串,如果沒有傳值,則返回null
Request::param(['name', 'email']); // 獲取多個參數值
其中,還有has方法可以檢測變量是否已經設置,如:
Request::has('id', 'get');
Request::has('name', 'post'); // 檢測是否有POST方法傳遞的name值,有的話返回true,反之為false。
變量檢測可以支持所有支持的系統變量,包括get/post/put/request/cookie/server/session/env/file
以上三種方法是TP6獲取參數的歸納總結,在很多情況下,我們需要判斷當前操作的請求類型是哪一種,如:GET、POST、PUT、DELETE或者是HEAD等等,同時不僅需要針對不同的請求類型做出相應的邏輯處理,更要兼顧安全性的驗證,過濾非法請求,TP6框架提供了請求對象Request類的多種方法來獲取、判斷當前請求類型,例如,判斷一個請求是否為POST請求,我們可以這樣做:
if($request->isPost()) {
// TODO
}
類似的情形還有$request->isGet()、$request->isPut()、$request->isAjax()等等,具體的方法如下圖:
請求對象Request類提供的方法
注意:method方法返回的請求類型始終是大寫的,并且這些方法都不需要傳入任何參數。
以上就是ThinkPHP6中獲取參數的三種方式,以及一些相關的請求類型,可能還不是很全,但是掌握這些基本能滿足大部分情形下的參數獲取,如果想了解更多相關內容,請移步ThinkPHP官網查看相關文檔。
文分享自華為云社區《淺談Tomcat之Servlet-request獲取請求參數及常用方法-云社區-華為云》,作者:QGS。
//獲取Map集合中所有的key
Enumeration<String> getParameterNames();
//獲取Map
Map<String, String[]> getParameterMap();
//根據key獲取Map集合中的vale (常用**)
String[] getParameterValues(String s);
//獲取value一維數組的第一個元素 (常用**)
String getParameter(String name);
瀏覽器向服務器提交的是String類型
//getParameterNames()獲取所有key值
Enumeration<String> keys = request.getParameterNames();
while (keys.hasMoreElements()){
String key = keys.nextElement();
System.out.print("key: "+key +" ");
//getParameterValues(key) 、據key獲取Map集合中的vale
String[] Values = request.getParameterValues(key);
if (Values.length>1){
for (String value : Values) {
System.out.print("value:"+value+" ");
}
}else {
System.out.print(Values[0]);
}
System.out.println();
}
如果html頁面的數據有更改,瀏覽器清除過緩存在執行。
//通過標簽中的name獲取value一維數組
String[] usernames = request.getParameterValues("username");
String[] pwds = request.getParameterValues("pwd");
String[] hobbies = request.getParameterValues("hobby");
for (String username : usernames) {
System.out.print(username);
}
System.out.println();
for (String pwd : pwds) {
System.out.print(pwd);
}
System.out.println();
for (String hobby : hobbies) {
if (hobby.isEmpty()){
System.out.println("null");
}
System.out.print(hobby);
}
System.out.println();
//獲取數組的第一個參數
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String hobby = request.getParameter("hobby");
System.out.println("getParameter :"+username+" "+pwd+" "+hobby);
//獲取數組的第一個參數
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String hobby = request.getParameter("hobby");
Request又稱“請求域”
應用域對象ServletContext(Servlet上下文對象)、
當用戶的共享數據很少修改操作并且數據量少的時候,使用ServletContext能夠提升程序的執行效率(應用域綁定數據,看作將數據放到Cache當中,用戶訪問時直接從Cache中提取,減少IO等操作)。
應用域對象ServletContext的操作方法(類似Map集合的操作)
//向域綁定數據
setAttribute(String name , Object obj)
//從域獲取數據,根據name(key)獲取數據
Object getAttribute(String name)
//移除數據,根據name(key)
removeAttribute(String name)
請求域對象
請求域比應用域的范圍小, 占用資源小,生命周期短,請求域對象只在一次請求內有效。
請求域對象ServletContext的操作方法(類似Map集合的操作)
//向域綁定數據
setAttribute(String name , Object obj)
//從域獲取數據,根據name(key)獲取數據
Object getAttribute(String name)
//移除數據,根據name(key)
removeAttribute(String name)
案例
//獲取系統當前時間
Date nowTime =new Date();
//向request域 中綁定數據
request.setAttribute("NowTime",nowTime);
//從request域 獲取數據
Object obj = request.getAttribute("NowTime");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = sdf.format((Date)obj);
out.print("當前時間: "+ timeStr);
public class ServletA extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用Servlet轉發機制。執行ServletA后,跳轉至ServletB,調用請求轉發器,將request,response參數傳遞給另一個HttpServlet子類
request.getRequestDispatcher("/servletB").forward(request,response);
}
}
public class ServletB extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取系統當前時間
Date nowTime =new Date();
//向request域 中綁定數據
request.setAttribute("NowTime",nowTime);
//從request域 獲取數據
Object obj = request.getAttribute("NowTime");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = sdf.format((Date)obj);
out.print("當前時間: "+ timeStr);
}
}
//既可以轉發Servlet類也可以轉發html(屬于Web容器當中合法的資源都可以轉發)
request.getRequestDispatcher("/share.html").forward(request,response);
//獲取客戶端的IP地址
String remoteAddr = request.getRemoteAddr();
//獲取遠程的用戶
String remoteUser = request.getRemoteUser();
//獲取遠程的主機IP
String remoteHost = request.getRemoteHost();
//獲取遠程的的端口
int remotePort = request.getRemotePort();
//獲取主機服務名
String serverName = request.getServerName();
//獲取服務路徑(項目名稱)
String servletPath = request.getServletPath();
//獲取服務端口
int serverPort = request.getServerPort();
//獲取Servlet上下文 或者this.getServletContext();
ServletContext servletContext = request.getServletContext();
//指定字符集(解決不同字符集亂碼問題)
response.setCharacterEncoding("utf-8");
點擊下方,第一時間了解華為云新鮮技術~
華為云博客_大數據博客_AI博客_云計算博客_開發者中心-華為云
#華為云開發者聯盟#
*請認真填寫需求信息,我們會在24小時內與您取得聯系。