现在我已经为此苦苦挣扎了一个星期,已经在互联网上搜索了,但是我无法成功。
上下文:我有一个带有2个选择列表的表单。我想要的是使用ajax不必每次我提交表单时都重新加载整个页面,并且用户选择保持不变。
当我在firefox中寻找devtools时,可以看到我想在页面上显示的确切响应。但是,该页面没有刷新/显示数据。...
这是我的第一个使用nodejs / ejs / mongodb / ajax的项目,我还没有足够的经验。在我的ajax请求的成功/完成部分中可能存在某些我不了解的东西...谁能帮我?如何显示,渲染我在devtool中服务器响应中看到的内容?
服务器部分:发布请求:app.js
编辑:我忘了提到我也有以下几行://为JSON请求设置BODY-PARSER:我的app.js文件中的app.use(bodyParser.json());
。
app.post('/games-query',urlencodedParser, (req, res) => {
console.log(req.body);
let titlepage = 'Games list :';
let platform = req.body.platformAjax;
let genre = req.body.genreAjax;
console.log('PLATFORM PARAM = '+ platform );
console.log('GENRE PARAM = '+ genre );
mameGames = [];
if ((genre == "") || (genre == "All")){
Game.find({gameplatform: platform}).sort({ gametitle: 1 }).limit(100).exec(function (err, games) {
var count = "results :"+games.length;
if(err){
console.error('could not retrieve games from DB');
res.sendStatus(500);
}else {
mameGames = games;
console.log("GAMES : "+mameGames.gametitle);
res.render('games', {games: mameGames, count: count, title:titlepage});
}
});
}else{
Game.find({gameplatform: platform, gamegenre:genre}).sort({ gametitle: 1 }).limit(100).exec(function (err, games) {
var count = "results :"+games.length;
if(err){
console.error('could not retrieve games from DB');
res.sendStatus(500);
}else {
mameGames = games;
// console.log('mameGames : ' + mameGames);
res.render('games', {games: mameGames, count: count, title:titlepage});
}
});
}
});
ajax请求(在/public/js/posrequest.js中:
$( document ).ready(function() {
function ajaxPost(){
const selectForm = document.getElementById('btnquery');
selectForm.addEventListener('click', (e)=>{
e.preventDefault();
let platform = document.getElementById('platformId').value;
let genre = document.getElementById('genreId').value;
let payload = {
platformAjax:platform,
genreAjax:genre
}
// DO POST
$.ajax({
type : "POST",
url : "games-query",
contentType : "application/json",
// data : {platformAjax:platform, genreAjax:genre},
data : JSON.stringify(payload),
dataType : "json",
}).done(function(data){
$('#gametitle').text(JSON.parse(data.gametitle));
return;
});
});
}
ajaxPost();
});
ejs文件:(在/views/games.ejs中):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>games</title>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="../public/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
<%- include ('./partials/header'); %>
<h2><%= title %></h2>
<h4 class="paddingBottom"><%= count %></h4>
<span class="forms form-group form-inline justify-content-center">
<div class="arrondi1">
<form class="form-inline form-search" action="/games" method="post">
<label for="byname" class="control-label label-padding">By Name:</label>
<input type="text" id="term" name ="term" class="form-control" placeholder="titre de jeu" width="1000px">
<button type="submit" class="btn btn-primary" id="btnSearch">Chercher</button>
</form>
</div>
<h5 class="between-forms">OR</h5>
<div class="arrondi2">
<form class="form-inline form-selection" id="selectForm" name="selectForm">
<label for="platform" class="control-label">By Platform:</label>
<select id="platformId" name="platformName" class="form-control" onsubmit="return false">
<option value = "Arcade" selected>Arcade</option>
<option value = "NeoGeo" >NeoGeo</option>
<option value = "SMS" >SMS</option>
<option value = "Genesis" >Genesis</option>
<option value = "Saturn" >Saturn</option>
<option value = "DC" >DC</option>
<option value = "NES" >NES</option>
<option value = "SNES" >SNES</option>
<option value = "NGC" >NGC</option>
<option value = "Wii" >Wii</option>
<option value = "WiiU" >WiiU</option>
<option value = "Switch" >Switch</option>
<option value = "PS1" >PS1</option>
<option value = "PS2" >PS2</option>
<option value = "PS3" >PS3</option>
<option value = "PS4" >PS4</option>
<option value = "PC" >PC</option>
</select>
<label for="genre" class="control-label ">And Genre:</label>
<select id="genreId" name="genreName" class="form-control" onsubmit="return false">
<option value = "" selected>All</option>
<option value = "shmup" >shmup</option>
<option value = "fighting" >fighting</option>
<option value = "beatThemUp" >beatThemUp</option>
<option value = "platform" >platform</option>
<option value = "lightgun" >lightgun</option>
<option value = "run&gun" >run&gun</option>
<option value = "race" >race</option>
<option value = "flight" >flight</option>
<option value = "puzzle" >puzzle</option>
<option value = "pinball" >pinball</option>
<option value = "sport" >sport</option>
<option value = "rpg" >rpg</option>
<option value = "adventure" >adventure</option>
</select>
<button type="submit" id="btnquery" class="btn btn-primary">Submit</button>
</form>
</div>
</span>
<div class = "main">
<div class="container">
<div class="row">
<% for(game of games){%>
<h4 class 'titre' id="gametitle"><a href="/games-details/<%= game._id %>"> <%= game.gametitle %></a></h4>
<h4 class 'titre' id="gametitleback"><%= game.gametitle %></h4>
<% } %>
</div>
</div>
</div>
<br>
<%- include ('./partials/footer'); %>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="/public/js/postrequest.js"></script>
<script>
let term = document.querySelector('#term');
const btnSearch = document.querySelector('#btnSearch');
</script>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/index.js"></script>
<script>loadProgressBar()</script>
</html>
example response i can see in the devtool (it is working)
编辑2:我看到这对任何人都不是显而易见的。我将隔离我的代码,以查看聚会中是否还有其他内容!
编辑3:自上周日发布以来,我做了很多新的测试。总是一样实际上我移动以下行:
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
进入我在w3school网站上看到的html标签。
我如何在页面中发送回复?
当我发送DC作为平台并将全部作为流派输入时,在firefox Web控制台中看到的内容确实如此:
HEADERS:
**Response headers:**
XHRPOSThttp://localhost:3000/games-query
[HTTP/1.1 200 OK 98ms]
URL de la requête :http://localhost:3000/games-query
Méthode de la requête :POST
Adresse distante :[::1]:3000
Code d’état :
200
Version :HTTP/1.1
En-têtes de la réponse (333 o)
En-têtes bruts
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: localhost:3000
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: text/html; charset=utf-8
Content-Length: 32157
ETag: W/"7d9d-m2EHsBSaOIu0E/Jr6q+X8UJQtdo"
Date: Tue, 19 May 2020 22:10:00 GMT
Connection: keep-alive
En-têtes de la requête (604 o)
En-têtes bruts
Accept
application/json, text/javascript, */*; q=0.01
Accept-Encoding
gzip, deflate
Accept-Language
fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Connection
keep-alive
Content-Length
36
Content-Type
application/json
Cookie
hblid=SAF2ExIBZf2cIdPG3m39N0O0…ID=7hvm3c3ie9k4ku9cue18777h82
DNT
1
Host
localhost:3000
Origin
http://localhost:3000
Referer
http://localhost:3000/games?platform=Arcade
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/76.0
X-Requested-With
XMLHttpRequest
参数:
JSON:
genreAjax ""
platformAjax "DC"
Transmission de la requete:
{"platformAjax":"DC","genreAjax":""}
响应/响应有效载荷:
<h4 class 'titre' id="gametitle"><a href="/games-details/5ebc645d200af104b4a9938d"> Ready 2 Rumble Boxing: Round 2</a></h4>
确定,
简而言之,我在ajax请求中使用的dataType是nodejs中的render方法的问题。
所以,我实际上是用来使它工作的:
// DO POST
$.ajax({
type : "POST",
url : "games-query",
contentType : "application/json",
data : JSON.stringify(payload),
success: (data) => {
console.log('ajax success!' );
$('.main').html(data);
}
});
我们可以使用:dataType:“ html”或dataType:“文本”或没有像我一样的dataType(因为如果没有声明dataType,我已经读过,jQuery将确定正确的dataType:):
jquery文档中的引号:
如果未指定,则jQuery将尝试根据响应的MIME类型来推断它(XML MIME类型将产生XML,在1.4中,JSON将产生一个JavaScript对象,在1.4脚本中,将执行该脚本,以及其他所有内容将以字符串形式返回)。可用的类型(以及作为第一个参数传递给您的成功回调的结果)是:有关更多信息,请参见文档:https://api.jquery.com/jQuery.ajax/
我还尝试从nodejs端用res.send()和res.json()替换res.render,但结果显示的结果不一样(它是整个对象),或者给我每个对象不可读的信息:[object:对象]。