I currently have a javascript variable called myVariableToSend that contains a single string and I need to send to my views where I can make raw SQL queries to gather corresponding data from the database and bring it back to my javascript. Here is what I have:
Javascript:
function scriptFunction(myVariableToSend){
$.getJSON("http://127.0.0.1:8000/getData/", myVariableToSend, function(serverdata){
window.alert(serverdata);
});
Views.py:
def getData(request):
some_data = request.GET(myVariableToSend)
cursor = connection.cursor()
cursor.execute("SELECT Car_ID FROM cars WHERE Carname = %s ", [some_data])
row = cursor.fetchall()
return JsonResponse(row, safe = False)
Urls.py:
url(r'^admin/', include(admin.site.urls)),
url(r'^$', startpage),
url(r'^getData/$', getData ),
I don't think my server side script(views.py) is working because when I run my server, I get a http500 error. Any help would be appreciated. Thank you.
UPDATE:
I have found that when I comment out my entire Views.py and only put
def getData(request):
return JsonResponse({"hello":"World"}, safe = False)
I get no problems and the AJAX request works. But when I have my original getData, it doesn't work. When I add this line in my views.py:
some_data = request.GET(myVariableToSend)
, I get an error and the data isn't displayed
If u want to send ur variables to function in view, u can capture it with url, like this:
$.getJSON('http://127.0.0.1:8000/getData/' + myVariableToSend +'/', function (serverdata) { //do ur work}
Then in urls.py you have:
url(r'getData/(?P<my_var>\w+)/$', views.get_data, name='get_data')
Then views.py:
def get_data(request, my_var):
#do ur work here
Answering the original question:
Your server is failing probably because bad syntax in views.py
some_data = request.GET(myVariableToSend)
myVariableToSend
is undefined here. So you should get it like this:
some_data = request.GET['myVariableToSend']
Besides the original question:
You'll get a lot of headaches if you try to set up your django app like this.You can query your database way easier if you use django's ORM. Read about it here .
Also, if you want to send the data in your models to your javascript code, you can save yourself lots of time by using a framework like Django REST Framework .
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.