I am building a web app, where a user can set a value to a specific number. It looks like that
<button type="button" class="btn btn-outline-primary" onclick="decrease()"> +1 </button>
<button type="button" class="btn btn-outline-primary" onclick="increase()"> -1 </button>
<script>
var a = 0;
function increase()
{
a--;
document.getElementById("val").innerHTML = a;
}
function decrease()
{
a++;
document.getElementById("val").innerHTML = a;
}
</script>
Now I would like add an other button like:
<button type="button" class="btn btn-outline-primary" onclick="send()"> send it </button>
But I don't really now how to send it (maybe I should use axaj and POST). I would like to access the value from my django view.py file and process it further and send it back (here it's GET).
How can I do it? Appreciate any help here
So I have found out how to do it.
html:
<button id="post-btn" class="btn btn-outline-primary"> test </button>
js:
var data = new FormData()
var a = 50;
var b = 100;
const button = document.getElementById('post-btn');
button.addEventListener('click', async _ => {
try {
data.append( "json", JSON.stringify(
{
'data1': a, /* var a = whatever */
'data2': b /* var b = whatever */
}
));
const response = await fetch('{% url "pulsox" %}', {
method: 'post',
headers: {
"X-Requested-With": "XMLHttpRequest"
},
body:data
});
}
catch(err)
{ window.alert('sth was wrong!'); }
});
view.py
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
def pulsox_view(request, *args, **kwargs):
if request.method == 'POST':
print(request.POST.get('json'))
a = request.POST.get('json')
print(a)
if request.POST.get( youritem):
# do you stuff
return render(request, your_page ,obj)
else:
return render(request,your_page,obj)
return render(request,your_page,obj)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.