简体   繁体   中英

Django/AJAX can't receive JSON

I'm trying to do a simple AJAX post which sends data to view and view calls another function and returns JSON with result. There is a problem. Console in Chrome inspect returns 403 Forbidden.

jquery-1.11.1.min.js:4 POST http://127.0.0.1:8000/check-url/ 403 (Forbidden)send @ jquery-1.11.1.min.js:4m.extend.ajax @ jquery-1.11.1.min.js:4(anonymous function) @ main.js:7m.event.dispatch @ jquery-1.11.1.min.js:3r.handle @ jquery-1.11.1.min.js:3
jquery-1.11.1.min.js:4 XHR finished loading: POST "http://127.0.0.1:8000/check-url/".send @ jquery-1.11.1.min.js:4m.extend.ajax @ jquery-1.11.1.min.js:4(anonymous function) @ main.js:7m.event.dispatch @ jquery-1.11.1.min.js:3r.handle @ jquery-1.11.1.min.js:3

It prints the data in the view ( print data ) but then it fails.

Do you know where is the problem?

def get_candidate_prices_and_xpaths(request):
    if request.method == 'POST':
        request_url =  request.POST.get('product_url','')
        data = scripts.get_prices_and_xpaths(request_url)
        print data
    return JsonResponse({x[0]:x[1] for x in data})

$(document).ready(function () {
    $("#button").click(function() {
        var request_url = '/check-url/';
        var product_url = $("#id_url").val();
        var post_data = {'product_url': product_url};

        $.ajax({
            type: "POST",
            url: request_url,
            data: post_data,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        })
    })
});

And this is the HTML:

<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
    <script src="{% static "js/main.js" %}"></script>
</head>
<body>
<form action="" method="POST">{% csrf_token %}
    {{ form.as_p }}
    <button id="button" type="submit" name="action" value="add_languages">Check</button>

</form>

</body>
</html>

I think Django's csrf exploit protection is at work. One work-around is to turn off the protection by decorating get_candidate_prices_and_xpaths with @csrf_exempt (ie add a line before this function with just '@csrf_exempt' on it, and also earlier in your file 'from django.views.decorators.csrf import csrf_exempt'). I had a similar problem with my API's. The better solution is to embed the relevant fragment in your page's template. The csrf Django feature is to avoid security exploits when browsing pages - the Django documentation explains more.

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.

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