2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
您在對另一個(gè)答案的評論中注意到,我仍然有一個(gè)白色的瀏覽器頁面,但沒有名稱和地址,這表明瀏覽器正在遠(yuǎn)離您當(dāng)前正在查看的頁面,因此,您沒有發(fā)出 Ajax 請求 - 或由于您沒有禁用默認(rèn)提交事件,您更有可能發(fā)出 Ajax 請求,但同時(shí)也發(fā)出標(biāo)準(zhǔn) HTTP Post 請求。
因此,您需要禁用默認(rèn)提交操作。
https://api.jquery.com/event.preventdefault/ https://www.w3schools.com/jquery/event_preventdefault.asp
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" id="submit" type="submit">
</form>
<p id="result"></p>
</body>
$('#submit').click(function(e){
e.preventDefault(); //prevent standard post
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
})

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
你錯(cuò)過了重點(diǎn):你有 $ajax 但應(yīng)該是$.ajax
您也可以提交表單而不是 json,例如:
function submitform(){
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
并在 servlet 中獲取參數(shù)“名稱”和“地址”:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
...
String name = request.getParameter("name");
String address = request.getParameter("address");
...
}
答案的變化
抱歉,我只關(guān)注警報(bào)消息的結(jié)論。Alan Hay 說得對,您可以使用它或?qū)㈩愋透臑榘粹o。無論如何,這是工作代碼
Servlet.java
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/jsonserverlet")
public class Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String jsonData = request.getParameter("per");
out.print(jsonData);
}
}
索引.jsp
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.js"
type="text/javascript"></script>
</head>
<body>
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="button" onclick="submitform()">
</form>
<p id="result"></p>
</body>
<script>
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
</script>
</html>
添加回答
舉報(bào)