Ajax, Asynchronous JavaScript and XML(異步JS和XML),
Ajax是一種無需重新加載整個網頁的情況下,能夠更新部分網頁的技術,
Ajax不是一種新的編程語言,而是一種用于創建更好更快以及互動性更強的Web應用程式的技術,
使用jQuery撰寫一個簡易的聯想器:
<html>
<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> //引入jQuery
</head>
<body>
<p>聯想:
<input type="text" id="text" >
<div id="think"></div>
</p>
<script>
//當輸入框中鍵盤彈起時,就會觸發
$('#text').keyup(function(){
$.ajax({
url:"http://localhost:8080/user/fun",
data:{"funname":$('#text').val()},
success:function(data){
$('#think').text(data.toString());
}
});
});
</script>
</body>
</html>
從中我們看出,ajax請求需要有三個必要的引數:
- url,即請求的地址
- data,請求的引數,可以放鍵值對
- success,回呼函式
另外,ajax請求默認是get方式,如果要用post,直接把請求方式從ajax改成post即可,
重要事件有:keyup(鍵盤彈起),onblur(失去焦點),click(點擊)
寫一個配套的后端:
@RestController
@RequestMapping("/user")
public class HelloController {
static Map<String,String> map=new HashMap();
static {
map.put("a","apple");
map.put("b","bird");
map.put("c","cat");
map.put("d","dog");
//此處省略
}
//沒起專案,直接從ftp請求http,會導致跨域問題,加上這個注解
@CrossOrigin
@GetMapping("/fun")
String fun(@RequestParam String funname){
//當文本框為空時,傳來的引數不是null,而是""
if (funname.equals("")){
return "";
}else{
return map.get(funname);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/295662.html
標籤:其他
上一篇:script標簽
