简体   繁体   中英

XMLHttpRequest error when using ajax in Django

I'm currently working on a webpage that has a form in the Django view. This form takes the name of an artist, a city, and a state in its input fields. These input values will eventually be concatenated to a url which links to a JSON file for concert data (when I get to that part), but currently, I'm just testing it out with hard coded values. The ajax call to this url should be made when the submit button is clicked (which I also haven't implemented yet), but for now, I'm just testing to see whether or not the ajax call itself will work. Here is the form (I'm using crispy forms, so I didn't add the input fields manually):

<form method= 'POST' action = ''>{% csrf_token %}
{{ form|crispy }}

<input type= 'submit' value= 'Submit'>

and the ajax call:

$.ajax({
    dataType:'json',
    url: 'http://api.bandsintown.com/events/search?artists[]=foals&location=New York,NY&radius=150&format=json&app_id=YOUR_APP_ID',
    success: function(data){
        //console.log(data);
        concertData = data;
        runMainProgram();
        $(data.tickets).each(function(index, value){
                console.log(value.p);
        });
    }
})

Here is the form for the page from forms.py:

class SearchForm(forms.Form):
    artist_select = forms.CharField()
    city = forms.CharField()
    state = forms.CharField()

I thought that since I added the {% csrf_token %} that the wouldn't be an error with cross origin referencing, but when I load the page, I'm getting the error:

XMLHttpRequest cannot load http://api.bandsintown.com/events/search?artists[]=foals&location=New%20York,NY&radius=150&format=json&app_id=YOUR_APP_ID. No 'Access-Control-Allow-Origin' header is present on the requested resource.

I may be misinterpreting the error, but it seems like that is the problem. How should I go about fixing this issue?

You have the error because you don't send the csrf_token in your request header:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
}  

var csrftoken = getCookie('csrftoken');

$.ajax({
    headers: {'X-CSRFToken': csrftoken}, // you add you token here
    dataType:'json',
    url: 'http://api.bandsintown.com/events/search?artists[]=foals&location=New York,NY&radius=150&format=json&app_id=YOUR_APP_ID',
    success: function(data){
        //console.log(data);
        concertData = data;
        runMainProgram();
        $(data.tickets).each(function(index, value){
                console.log(value.p);
        });
    }
})

Check Ajax with Django

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