gpt4 book ai didi

javascript - POST请求后,不要进入成功回调(javascript)

转载 作者:行者123 更新时间:2023-12-01 04:03:18 25 4
gpt4 key购买 nike

我的问题是请求 post 请求的页面消失了,然后只向我显示来自服务器的 JSON 数据字符串。请让我知道如何在不重定向(?)页面的情况下获取响应数据。

客户端 POST 请求

<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login Form</title>

<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="../../semantic/dist/semantic.min.css">
<link rel="stylesheet" type="text/css" href="../../semantic/dist/login.css">
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="semantic/dist/semantic.min.js"></script>


<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var form_data = {
user_id: $("#user_id").val(),
user_pw: $("#user_pw").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: '/',
data: JSON.stringify(form_data),
contentType: "application/json",
dataType: "json",
success: function(response) {
console.log('test');
},
error : function(response){
console.log('test');
}
});
});
});
</script>
</head>

<body>
<div class="ui one column center aligned grid">
<div class="column six wide form-holder">
<h2 class="center aligned header form-head">Sign in</h2>
<div class="ui form">
<form class="form-signin" method="post">
<div class="field">
<input type="text" name = "user_id" placeholder="Email">
</div>
<div class="field">
<input type="password" name = "user_pw" placeholder="password">
</div>
<div class="field">
<input type="submit" value="sign in" class="ui button large fluid green">
</div>
<div class="field">
<CENTER><h5><a href = "/register">Register</a></h5></CENTER>
</div>
</form>
</div>
</div>

服务器 POST 响应

res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({message : "success"}));

结果
{“消息”:“成功”}

最佳答案

为了防止重定向,您应该使用 PreventDefault() 函数。

 <script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {
user_id: $("#user_id").val(),
user_pw: $("#user_pw").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: '/',
data: JSON.stringify(form_data),
contentType: "application/json",
dataType: "json",
success: function(response) {
console.log(response); //->it is not working.
},
error : function(response){
console.log('fail');
}
});
});
});
</script>

关于javascript - POST请求后,不要进入成功回调(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42019900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com