【发布时间】:2018-09-26 00:22:10
【问题描述】:
我正在使用 jquery ajax 将 json 数据导入我的网页(Django 框架)。我似乎无法呈现 json 数据(我的第一步只是做一个 console.log(data)-not working)。我得到了一种“未知”类型,所以我认为这可能是问题的一部分或全部。在我的简单模板中,我有一个按钮,可以进行无效的 ajax 调用。下面的代码包括我的 urls.py 文件、带有相关功能的 views.py 文件以及我网站上的 ajax 代码。 Firefox 开发人员页面上的网络选项卡显示代码 200,我假设这意味着我的 urls.py 和 views.py 是正确的,但如果这是真的,请告诉我。我的应用程序在 pythonanywhere 上。如果ajax调用可以调出json数据,我正在使用console.log。它没。我的 javascript 触发了错误代码——不确定乳清。感谢您提供的任何帮助。
urls.py(见最后一个网址):
app_name = 'beach'
urlpatterns = [
url(r'^$', views.index,name='index'), #when you go to the beach directory, it looks at this urls.py file, this says go to views.py in this folder, index function
url(r'^(?P<lakes>[a].*)/$', views.searched, name='lakes'), #regex = starts with a letter then it can be anything
url(r'^(?P<gnisid>[0-9]+)/$', views.gnis, name='GNIS'), #regex = numbers ony, many. name-'GNIS' a link to the HTTPResponseRedirect or directly from the template from a link
url(r'^(?P<tmap>tmap)/$', views.tmap, name='tmap'),
url(r'^(?P<profile>profile)/$', views.profile, name='profile'),
url(r'^(?P<ajax>profiles/default)/$', views.defaultajax, name='ajaxgnis')
]
views.py
def defaultajax(request, ajaxgnis):
x = {"foo": "bar"}
jsondata = json.dumps(x)
return HttpResponse(jsondata, content_type='application/json')
带有 javascript 代码的模板(大量测试,抱歉)
window.onload = function () {
$('#putprofile').click(makeProfile);
function makeProfile(){
$.ajax({
url: "/beach/profile/default/",
dataType: "json",
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
console.log('datatype:');
console.log(typeof data);
},
success: function(data, textStatus, jqXHR) {
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('data:');
console.log(data);
}
});
}
}
【问题讨论】:
-
从您的问题中不清楚您提到的错误来自哪里。它在成功功能中吗?你是什么意思“console.log(数据)”不起作用?这是引发错误的原因吗?它只是没有记录任何东西吗?
-
感谢您的回复。当我单击按钮并运行 makeProfile 函数时,会触发错误警报而不是成功警报。如果成功,该函数应该将数据(在views.py中看到)记录到控制台。数据不会记录到控制台。
-
另外,在错误中,我正在记录数据类型,它显示为“未知”。我认为这应该是 json。
-
你能从firefox网络标签看到响应正文的内容吗?你说响应返回 200 OK,所以正文本身可能会提供一些线索。
-
意志。我不这么认为。这是我的网站网址:beachtemp.us/beach/profile.