简体   繁体   English

SyntaxError:位置1中的JSON中的意外令牌<

[英]SyntaxError: Unexpected token < in JSON at position 1

I am learning ajax with Django. 我正在用Django学习ajax。 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. 这是我的代码,但它在控制台中的位置1的JSON中记录了SyntaxError:Unexpected token <in JSON 。我尝试编辑csrf_token部分,但是没有任何好处。 What can be the possible glitches in my code? 我的代码中可能出现的故障有哪些?

index.html 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 views.py

@csrf_exempt
def convert(request):
    value = request.GET.get('value', None)
    data = {
        "googletrans":  "prateek"
    }
    return JsonResponse(data)

urls.py 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. 我认为您的错误可能出在您的URL定义中。 Try to change the first pattern from '' to '^/' . 尝试将第一个模式从''更改为'^/'

urlpatterns = [
    url('^/', views.home, name='home'),
    ...
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM