通过XMLHttpRequest获取Python后端返回的JSON数据失败如何解决?
问题解决方法
核心问题梳理
- Django类视图用法错误:当前业务逻辑直接写在类的属性定义区域,只会在类加载时执行一次,请求到达时不会触发。Django的DetailView默认会返回渲染后的HTML模板内容,这就是你拿到完整HTML响应的原因。
- 响应格式不规范:即使使用
sys.stdout输出,Content-Type头部后必须加2个换行符和响应体分隔,否则浏览器无法正确识别内容类型。 - 原生XMLHttpRequest默认不会自动生成
responseJSON属性,需要额外配置或手动解析。
Python端修改方案
直接使用Django内置的JsonResponse返回响应,自动处理响应头和JSON序列化逻辑,不要手动用sys.stdout输出:
import json from django.views.generic import DetailView from django.http import JsonResponse from .models import Map # 替换为你自己的Map模型导入路径 class MapDetailView(DetailView): model = Map def get(self, request, *args, **kwargs): # 业务逻辑必须写在请求处理方法内,每次GET请求都会执行 map_data = json.loads('{"name": "woods", "size": 1000}') fail = 0 try: myData = json.dumps(map_data) except: fail = 1 else: if myData == "": fail = 1 if fail == 1: return JsonResponse({"msg": "Who are you?"}, status=400) # JsonResponse自动设置Content-Type为application/json return JsonResponse(json.loads(myData))
JavaScript端修改方案
两种方案二选一即可:
方案1:手动解析响应文本
function callAjax(url) { var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // 手动将字符串响应转为JSON对象 const res = JSON.parse(xmlhttp.responseText); console.log(res); } } xmlhttp.open("GET", url, true); xmlhttp.send(); } callAjax('http://127.0.0.1:8000/catalog/map/1');
方案2:配置响应类型自动解析
function callAjax(url) { var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.responseType = 'json'; // 新增这行配置,让浏览器自动解析JSON xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log(xmlhttp.response); } } xmlhttp.open("GET", url, true); xmlhttp.send(); } callAjax('http://127.0.0.1:8000/catalog/map/1');
内容的提问来源于stack exchange,提问作者code_pizza
相关产品推荐
相关产品推荐

