我有一个python字符串,它是javascript代码,我也想将此字符串作为字符串传递给javascript。
我的想法是将python字符串传递给javascript字符串,然后在javascript中使用eval()函数将该字符串转换为实际代码并执行它。
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
var code = "{{success}}"
console.log(code) // return Uncaught SyntaxError: Invalid or unexpected token
我也尝试过像这样将字符串作为json传递
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
success = json.dumps(success)
return render(request, "app/login.html", {'success': success})
var code = JSON.parse("{{success|safe}}");
console.log(code) //return Uncaught SyntaxError: missing ) after argument list
我尝试过的最后一件事是
def login(request):
success = '''
window.location = '{% url 'home' %}';
# some other codes
'''
return render(request, "app/login.html", {'success': success})
<h3 id="success_id" hidden>{{success}}</h3>
<script>
var code = $("#success_id").text();
console.log(code) //return window.location = "{% url 'home' %}"
// if i do this
var code = "window.location = '{% url 'home' %}'";
console.log(code) // return window.location = /app/home/
// I want it to return the url like /app/home
</script>
我怎样才能做到这一点?
好的,从本质上来说,您想要使用Django将数据传递给js吗?
这与Django创建一个Json Response有关,然后JavaScript会发出一个请求,实质上是在使用某些API。
您编写了render函数的视图代码将不再需要...
就像是
JsonResponse({'success':success})
从'django.http'导入JsonResponse之后将需要
然后在js文件中,您将不得不使用Ajax调用url及其必需的方法来获取所需的数据。
在您的脚本标签中,您将需要这样的内容
const xhr= new XMLHttpRequest ()
xhr.open('django_url', 'method')
xhr.onload = function () {
const msg = xhr.response.success
}
xhr.send()
如果您熟悉fetch或axios,则可以使用您选择的任何库。
django_url指的是连接该视图的URL,该方法指的是http_method,即“ GET”或“ POST”(最常用)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句