【发布时间】:2021-06-02 11:27:48
【问题描述】:
我有这个功能可以将用户特定的数据制成表格。它是一个发送查询参数 userId 的 get 方法:
<script>
let thisArray = []
let = userId = $('#userId').val();
$.ajax({
method:'GET',
url:'/auth/marcacoesGET/:userId',
dataType: 'json',
data: {
userId: userId
},
success:function(marcacao){
thisArray = marcacao
buildTable(thisArray);
console.log(thisArray)
}
})
function buildTable(marcacao){
let table = document.getElementById('tabelaCliente')
for(let i = 0; i < marcacao.length; i++){
let row = `<tr>
<td>${marcacao[i].address}</td>
<td>${marcacao[i].date}</td>
<td>${marcacao[i].hour}</td>
<td>${marcacao[i].type}</td>
<td>${marcacao[i].state}</td>
</tr>`
table.innerHTML += row
}
}
</script>
我希望这个函数将 userId 传递给这个 get 方法:
这是一条路线
router.get('/marcacoesGET/:userId', authControllerMarcacao.getMarcacoes);
这就是get方法。
exports.getMarcacoes = async(req, res) => {
const { userId } = req.params;
try {
const user = await User.findById({_id : userId}).populate('marcacaoCliente');
console.log('user', user);
res.status(200).json(user.marcacaoCliente);
} catch (err) {
res.json({message:err});
}
我在浏览器控制台上收到了这条奇怪的消息,IDK 是否有错误:
Object { message: {…} }
message: Object { stringValue: "\"{ _id: ':userId' }\"", kind: "ObjectId", path: "_id", … }
kind: "ObjectId"
path: "_id"
reason: Object { }
stringValue: "\"{ _id: ':userId' }\""
value: Object { _id: ":userId" }
<prototype>: Object { … }
<prototype>: Object { … }
__defineGetter__: function __defineGetter__()
__defineSetter__: function __defineSetter__()
__lookupGetter__: function __lookupGetter__()
__lookupSetter__: function __lookupSetter__()
__proto__:
constructor: function Object()
hasOwnProperty: function hasOwnProperty()
isPrototypeOf: function isPrototypeOf()
propertyIsEnumerable: function propertyIsEnumerable()
toLocaleString: function toLocaleString()
toString: function toString()
valueOf: function valueOf()
<get __proto__()>: function __proto__()
<set __proto__()>: function __proto__()
如果您需要更多信息,请告诉
【问题讨论】:
-
在 ajax 调用中你不应该提供用户 ID 而不是
:userId吗?例如这个url:'/auth/marcacoesGET/:userId',改成这个url:'/auth/marcacoesGET/1', -
确实,您请求的是
/auth/marcacoesGET/:userId?userId=1。但是,您需要的客户端 ajax URL 是"/auth/marcacoesGET/" + userId您看到的浏览器控制台输出是来自服务器数据库查询的错误对象。 -
@ciekals11 好的,我该怎么做才能读取当前登录用户 ID?
-
您在问如何将变量插入字符串...(实际上是附加它,这更简单)另外,您应该在浏览器控制台中打开
xhr过滤器,以便您可以仔细检查ajax URL、请求和响应 -
另外这个:
let = userId = $('#userId').val();出人意料地工作,但应该是let userId = $('#userId').val();
标签: javascript jquery node.js ajax express