简体   繁体   中英

How to call python function from javascript with ajax in django

I want to display the range of the selected car without refreshing the page. This code doesn't give an error but also doesn't do the trick.

index.html

<select class="custom-select d-block w-100" name="car" id="car" onchange="display(this.value)">
                {% for car in cars_list%}
                    <option value="{{ car }}">{{ car }}</option>
                {% endfor %}
</select>

main.js

function display(value){
$.ajax({
type: "POST",
url: "/get_car_data/",
data: { car_model: value}
}).done(function(range) {
    alert("test")
    $("#range").html(range);
});
}

ajax_handler.py

def get_car_data(car_model):
cars_frame = pd.read_csv("C:/Users/David/Desktop/cars.csv", sep=';')
frame2 = cars_frame.set_index('Car', drop=True)
car_range = (frame2.loc[car_model]['Range'])
return car_range

urls.py

urlpatterns = [
url(r'^get_car_data/', ajax_handler.get_car_data, name='get_car_data'),]

The big issue I am seeing here, barring code that I am not privy to, is that your view (which is hard to read because it's lost all indenting) is missing two things:

1) Any way to accept parameters via post. The normal signature you'd expect for a view is:

def get_car_data(request, car_model):
    ```your code here```

In that case, the car model would be part of the url itself, not a post request and you'd just do an AJAX get to the url with the appropriate model name (or given that names may have odd characters, maybe a lookup by primary key instead). You can also get at POST values using request.POST as a dictionary in which case omit the parameter car_model and get it out of the POST dict.

2) Any way to serialize it that would result in a returned HTTP Response. If you're expecing HTML to plop in, this could be as simple as an HttpResponse object that returns a string with the info or even a template using render . But you need something there.

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