實現效果:輸入用戶名和年齡,點擊按鈕,可把數據提交到后台(如上圖:數據被提交到myeclipse的console里面)。
第一個按鈕是用js方法提交,第二個按鈕用jquery方法。
用到的工具:webstorm+myeclipse
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/jquery-3.1.1.min.js"></script>
</head>
<body>
用戶名:<input type="text" id="name"><br>
年齡: <input type="text" id="age"><br>
<button onclick="get()">傳數據到后端</button>
<button id="jquery">jquery的ajax提交</button>
<script>
//js傳送方法
function get() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var xml = new XMLHttpRequest();
xml.open("get","http://localhost:8080/Test/servlet/TestServlet?one="+name+"&two="+age,true);
xml.onreadystatechange = function () {
};
xml.send();
}
//jquery提交的ajax
$("#jquery").click(function () {
var name = $("#name").val();
var age= $("#age").val();
//第一種傳參數的寫法
$.get("http://localhost:8080/Test/servlet/TestServlet?one="+name+"&two="+age,function (data) {
console.log(data);
})
//第二種傳參數的寫法
$.get("http://localhost:8080/Test/servlet/TestServlet",{one:name,two:age},function (data) {
console.log(data);
})
})
</script>
</body>
</html>