功能:
此代码的功能是更新用户个人资料页面上的用户详细信息。
代码:
Profile.ejs
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
//alert(json);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}, false);
});
})();
</script>
<div id="res">
<h4>
<%= status %>
</h4>
</div>
<form id="test" action="/profile" method="post">
<input type="text" name="name" id="name" value=""/>
<input type="text" name="about" id="about" value=""/>
<input type="text" name="hobbies" id="hobbies" value=""/>
<input type="submit" value="send" class="btn btn-primary btn-block"/>
</form>
Index.js
router.get('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:''});
});
router.post('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:'Changes Updated'});
});
预期结果:
发送包含所有详细信息的发布请求后, <div id="res">
应包含文本更改已更新。
实际结果:
发送 post 请求后,会观察到 200 OK 响应,并且响应数据包包含文本 Changes Updated。然而,浏览器并没有反射(reflect)它。收到的新响应不会呈现。
请协助解决这个问题,因为我对此还很陌生(整个代码是从很多地方组合在一起的)。此外,任何额外的信息或有关该主题的良好阅读将不胜感激
最佳答案
您将需要使用 jQuery html
属性将所需结果插入到 div 中。 ejs 用于在页面加载之前创建模板,而不是在页面加载后插入 ajax 数据。
试试这个:
$(document).ready(function() { //the jQuery equivalent
var form = $('#test');
form.on('submit', function(e) {
e.preventDefault();
var json = toJSONString(this);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(data) {
console.log(data);
$('#res').html(data); //insert "data" into the inner html of the div
},
dataType: "json",
contentType : "application/json"
});
}, false);
});
});
关于javascript - 在 NodeJs 中呈现 jquery POST 请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764317/