我想在Django中在不单击页面刷新的情况下单击按钮时调用函数,因此我正在使用AJAX,但它不起作用。我之前还不了解AJAX,但我是其中的新手,但这是经过3天的测试后我所管理的:
Views.py可以运行,但AJAX函数不能运行。
它打印Ups, NOT AJAX
views.py:
bot = Instagram()
def instabot(request):
template = 'instabot.html'
return render(request, template)
def runinstabot(request):
print('Welcome here')
if request.method == 'POST':
runinstabot.login = request.POST.get('login')
runinstabot.password = request.POST.get('password')
if request.is_ajax():
bot.login(runinstabot.login, runinstabot.password)
bot.search()
else:
print('Ups, NOT AJAX')
print(request.POST)
return HttpResponse('')
instabot.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>test bot</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
TEST:
<form id='runbot' action='/runinstabot/' method="post" >
{% csrf_token %}
<input type='text' id='login' />
<input type='text' id='password' />
<input type="submit" value="Submit">
</form>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">
$('runbot').on('submit', function(event){
event.preventDefault();
$.ajax({
type:"POST",
url: "{ url 'runinstabot' }",
data: {
login:$('#login').val(),
password:$('#password').val(),
csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
},
});
});
</script>
</html>
urls.py:
url(r'^instabot/', instabot, name='instabot'),
url(r'^runinstabot/', runinstabot, name='runinstabot'),
Instagram()
是使用Selenium自动执行某些操作的python代码
我会推荐所有建议