Ошибка разбора JSON в сценарии ajax с использованием фреймворка Django Rest
Я использую django rest framework. Мои представления отвечают нормально, но когда я отправляю представление с помощью ajax, оно выдает ошибку json parse error.
Here is my views.py file:
@api_view(['GET', 'POST'])
@parser_classes([JSONParser])
def signup(request, format=None):
if request.method == 'POST':
data = JSONParser().parse(request)
username = data.get('username')
first_name = data.get('first_name')
last_name = data.get('last_name')
email = data.get('email')
password = data.get('password')
gender = data.get('gender')
birth_date = data.get('birth_date')
serializer = UserSerializer(data=data)
if serializer.is_valid():
user = User.objects.create_user(username=username,first_name=first_name,last_name=last_name,email=email,gender=gender,birth_date=birth_date)
user.set_password(password)
user.save()
data = {'result': 'success', 'message':'You have registered successfully now you can login'}
return Response(data=data, status=201)
elif not serializer.is_valid():
data = { 'result': 'error', 'message':serializer.errors}
return Response(data=data)
if not request.user.id and request.method == 'GET':
return render(request, 'sessionauthapp/signup.html')
My ajax js script:
var frm = $('#signupform');
var token = '{{csrf_token}}';
$('#signupform').on('submit', function(e) {
e.preventDefault();
$.ajax({
headers: { "X-CSRFToken": token },
url: '/signup/',
type: 'post',
data: $(this).serialize(),
dataType: "json",
contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function(data) {
}
});
return false;
});
My ajax script gives me an error like json parse error but my views response is ok.
Мой скрипт ajax выдает ошибку типа json parse error, но ответ представления в порядке. Здравствуйте, я использую django rest framework.My views response is ok but when i submit my view using ajax it gives me an error json parse error.
This is my question and i solved it here is my valid script Firstly, convert my form data into json serialize objects with the help of each() and Json.stringify with respective names and values of form:
var frm = $('#signupform');
var token = '{{csrf_token}}';
$('#signupform').on('submit', function(e) {
e.preventDefault();
var formDataObj = {};
(function() {
frm.find(":input").not("[type='submit']").not("[type='reset']").each(function() {
var thisInput = $(this);
formDataObj[thisInput.attr("name")] = thisInput.val();
});
})();
$.ajax({
headers: { "X-CSRFToken": token },
url: '/signup/',
method: 'post',
// data: $(this).serialize(),
data: JSON.stringify(formDataObj),
dataType: "json",
contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function(data) {
}
});
return false; });