Ajax-запрос в django
Мой код ajax
$.ajax({
type: "get",
url: "",
statusCode: {
500: function() {
alert("error");
}},
data: {
"map":JSON.stringify(jsonmap),
"road":JSON.stringify(sourceGoal),
"line":JSON.stringify(straightLineToDestination)
},
success: function(response){
alert("success")
}
});
мой код views.py :
import json
from telnetlib import STATUS
from urllib import request
from django.shortcuts import render
from django.http import HttpResponse
import os
from django.views.generic import View
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from .algocode import a_star
import pprint
@csrf_exempt
def home_view(request):
if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
if request.method == 'Get':
straight_line=json.loads(request.Get.get('line'))
SourceandGoal=json.loads(request.Get.get('road'))
Graph=json.loads(request.Get.get('map'))
heuristic, cost, optimal_path = a_star(SourceandGoal["start"], SourceandGoal["end"],Graph,straight_line)
result=' -> '.join(city for city in optimal_path)
print(result)
print(heuristic)
print(cost)
return JsonResponse({"heuristic":heuristic,"cost":cost,"result":result})
return render(request,'index.html')
Мой URLS.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',home_view),
]
мои проблемы:
- Когда тип ajax был "post", у меня была "500 вечная ошибка сервера", но данные передаются, и я могу получить к ним доступ и использовать их как хочу в моем views.py .
Я изменил тип ajax на "get", ошибок не было
.
теперь я получаю данные в неправильном формате и не могу использовать их в своем проекте
"GET /? map=%22%7B%5C%22City1%5C%22%3A%7B%5C%22City2%5C%22%3A123%7D%2C%5C%22City2%5C%22%3A%7B%5C%22City1%5C%22%3A12%7D%7D%22& road=%7B%22start%22%3A%22City1%22%2C%22end%22%3A%22City2%22%7D&line=%7B%22City2%22%3A32%2C%22City1%22%3A222%7D HTTP/1.1" 200 1247
когда тип ajax был "post", данные, которые я получаю, приходят вот так, даже с сервером Erorr :
{ Город1: {Город2: 123} Город2: {Город1: 12} }
Спасибо за помощь