I am learning ajax with Django. This is my code but it logs SyntaxError: Unexpected token < in JSON at position 1 in my console.I tried editing the csrf_token part but nothing good could come. What can be the possible glitches in my code?
index.html
...
<form class="form-inline" action="translate/" method="post">
{% csrf_token %}
{{ form }}
<div class="form-group">
<input type="textarea" class="form-control email" id="email" placeholder="Enter text" name="string" autofocus="">
</div>
<button type="submit" class="btn btn-success pull-right">Convert</button>
</form>
...
<script>
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$("#email").keyup(function () {
var value = $(this).val();
$.ajax({
type:"POST",
url: '/translate/',
data: {
"value": value,
},
dataType: 'json',
success: function (data) {
alert(":)");
console.log(data);
{#$("#googletrans").html(data.googletrans);#}
},
error: function(xhr, status, error) {
alert(error);
console.log(error);
}
});
});
</script>
views.py
@csrf_exempt
def convert(request):
value = request.GET.get('value', None)
data = {
"googletrans": "prateek"
}
return JsonResponse(data)
urls.py
urlpatterns = [
url('', views.home, name='home'),
url(r'^translate/$', views.convert, name='convert'),
]
I think your error may be in your URL definitions. Try to change the first pattern from ''
to '^/'
.
urlpatterns = [
url('^/', views.home, name='home'),
...
]
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.