当我按下“登录”按钮时,将调用提交功能。 由于某种原因,应该显示的信息将在新选项卡中打开 但它不应该。
我正在火花服务器上显示信息。
任何想法为什么?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- load bootstrap for nicer ui -->
<!-- <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">-->
</head>
<body>
<div class="container">
<h1>Hello, world!</h1>
<form method="post" action="/print" class="form-inline" role="form">
<div class="form-group">
<input type="text" class="form-control" name="y" id="y" placeholder="Y-Hnit">
</div>
<div class="form-group">
<input type="text" class="form-control" name="x" id="x" placeholder="X-Hnit">
</div>
<div class="form-group">
<input type="text" class="form-control" name="player" id="player" placeholder="playerid">
</div>
<button type="submit" class="btn btn-default">Sign in</button>
</form>
<hr>
<div id="results">
</div>
</div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- use ajax to submit form, retreive the result and display on the page -->
<script>
$(document).ready(function() {
var form = $('form');
form.submit(function(e) {
var y = $("#y")val();
var x = $("#x").val();
var player = $("#player").val();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: 'y=' + y + '&x=' + x + "&player" + player
}).done(function(String) {
$('#results').html(String).attr('class', 'alert alert-success');
}).fail(function(String) {
$('#results').html("bluuu").attr('class', 'alert alert-danger');
});
e.preventDefault();
});
});
</script>
</body>
</html>
答案 0 :(得分:1)
在表单id
中添加id="form"
,您的脚本应如下:
$(document).ready(function(){
$(document).on('submit','#form',function(){
var info = $('#form').serialize();
$.ajax({
type: "POST",
url: /print,
data: info,
success: function(data){
if(data){
$('#results').html(data).attr('class', 'alert alert-success');
}else{
$('#results').html("bluuu").attr('class', 'alert alert-danger');
}
}
});
});
});
修改:确保功能print
检查是否存在ajax回复else
将返回null
。