[英]Redirecting to a url with an id in it, based on what the user clicks
I have read other solutions and none of them have helped. 我已经阅读了其他解决方案,但都没有帮助。 So the idea is, users send messages, those messages have replies, to view the relpies it redirects users to
/reply/<message_id>
when the user clicks a hyperlink. 因此,想法是,用户发送消息,这些消息具有回复,以查看当用户单击超链接时将用户重定向到
/reply/<message_id>
的关联。 I have attached the relevant code below. 我已在下面附上了相关代码。
app.py: app.py:
@app.route('/reply/<message_id>')
def reply(message_id):
return render_template('reply.html', message_id = message_id)
index.html: index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
var message_id = 0 ;
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
message_id++
e.preventDefault()
let user_input = $( 'input.message' ).val()
socket.emit( 'my event', {
message_id : message_id,
message : user_input
} )
$( 'input.message' ).val( '' ).focus()
} )
} )
console.log("we are before the method,a nd mid is " + mid + " of type " + typeof mid)
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.message_id !== 'undefined' ) {
$( 'h3' ).remove()
console.log("msg.message_id is " + msg.message_id + typeof msg.message_id)
var mid = msg.message_id
console.log("we are before the method,a nd mid is " + mid + " of type " + typeof mid)
$( 'div.message_holder' ).append( '<div>'+mid+' '+msg.message+' <a href="{{ url_for('reply', message_id='X') }}"'.replace('X', mid)'>reply</a></div>' ))
}
})
</script>
reply.html Reply.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>The reply </title>
</head>
<body>
<h1>Hello, your message id was {{ message_id }}!</h1>
</body>
</html>
What is happening at the moment, is when I click reply
it redirects me to /reply/
and then says cannot be found. 目前发生的是,当我单击“
reply
它将我重定向到/reply/
,然后说找不到。 I expect it to redirect me to /reply/2
or whatever message id I click on. 我希望它会将我重定向到
/reply/2
或任何我单击的消息ID。 Thanks for any help 谢谢你的帮助
Assuming mid
is a javascript variable, you can't mix this with Jinja code. 假设
mid
是一个javascript变量,则不能将其与Jinja代码混合使用。 The Jinja rendering will interpret mid
as a Python variable, which in your case has not been set at the time of rendering. Jinja渲染将把
mid
解释为一个Python变量,在您的情况下,在渲染时尚未设置该变量。
To solve, move the variable out of the Jinja code. 要解决此问题,请将变量移出Jinja代码。 To keep the
url_for
working, you'll need to still provide a value for message_id
. 为了使
url_for
正常工作,您仍然需要为message_id
提供一个值。 For example: 例如:
...' <a href="{{ url_for('reply', message_id='X') }}"'.replace('X', mid) + '>...'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.