Suppose I have the following function in my django project. getValues2() returns a list with numbers. How can I pass this numbers to my view using window.location?
<script>
let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get();
console.log('getValues2 ',getValues2())
window.location('eprint/checked' + getValues?()
</script>
views.py
def eprint(request):
print('eprint')
# how to get the list from jquery?
print(checked)
In your JS
Also you need the JS Cookie library for CSRF if you want protection ( https://docs.djangoproject.com/en/3.2/ref/csrf/; https://github.com/js-cookie/js-cookie/ )
<script>
let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get();
console.log('getValues2 ',getValues2())
async function send_to_view(){
const csrftoken = Cookies.get('csrftoken');
let response = await fetch(`${url_to_eprint}`, {
method: 'POST',
headers: {
'Content-type':'application/json',
'X-CSRFToken': csrftoken,
},
// JS sends as a string to back end
body: JSON.strigify(getValues2)
})
let data = await response.json()
return data
}
send_to_view()
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
//window.location('eprint/checked' + getValues?()
</script>
In your views.py
import json
from djano.http import JsonResponse
def eprint(request):
# post request comes in the body of the request
print(request.body)
# have to unpack it from a string into a dictionary
checked = json.loads(request.body)
print('eprint')
# how to get the list from jquery?
print(checked)
return JsonResponse({"status":"Okay"})
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.