![](/img/trans.png)
[英]Rails adblock JS file behaving differently in production / development
[英]External JS file behaving differently
因此,在制作一个使用 python、js 和 flask-socketio 广播动态生成的列表项的简单网页时,js 代码在作为外部文件引用时表现不同,而在 html 文件中内联编写时它可以完美运行。 这是代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<title>Flack</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
alert('hello');
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
socket.on('connect', () => {
document.querySelector('#add').onsubmit = () => {
var v = document.querySelector('#chname');
const channel = v.value;
v.value = '';
socket.emit('add channel', {'channel': channel});
return false;
}
});
socket.on('new channel', data => {
const li = document.createElement('li');
li.innerHTML = data['channel'];
document.querySelector('#channels').append(li);
});
});
</script>
</head>
<body>
<header>
<h1>Welcome to Flack</h1>
</header>
<p>Join the existing channels or create a new one to have a chit chat with the internet friends.</p>
<form id= "add">
<input type="text" autocomplete="off" id="chname" placeholder="Channel Name"/>
<button type="submit" id= "submit">Add</button>
</form>
<ul id= "channels">
{% for channel in channels %}
<li>{{ channel }}</li>
{% endfor %}
</ul>
</body>
</html>
警报 function 在这两种情况下都可以正常工作,但表单操作却不行。 是的,我也尝试在 body 标记的末尾引用我的 js 文件(../static/index.js)。 以下是 application.py 的代码,以备不时之需:
import os
import requests
from flask import Flask, request, render_template, jsonify
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
channels = []
user = False
@app.route("/")
def index():
return render_template('index.html', channels=channels)
@socketio.on('add channel')
def add(data):
channels.append(data['channel'])
emit("new channel", {'channel': data['channel']}, broadcast=True)
if __name__ == "__main__":
socketio.run(app, debug= True)
这应该有助于您的表单不提交
document.querySelector('#add').onsubmit = (event) => {
event.preventDefault();
var v = document.querySelector('#chname');
const channel = v.value;
v.value = '';
socket.emit('add channel', {'channel': channel});
return false;
}
这应该可以解决您的表单无法运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.