回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>它是服务器端问题<a href="https://stackoverflow.com/questions/40744156/internal-error-on-ajax-call-to-a-django-view-restframework-endpoint/40744441#40744441">Internal error on AJAX call to a Django view (restframework endpoint)</a>的延续。现在有一个前端问题。在</p>
<pre><code>$.ajax({
url: '/notify/',
type:'GET',
dataType: '',
success: function (data) {
if (data.notifications) {
console.log(data.notifiications[1].fields);
}
}
});
</code></pre>
<p>在控制台中获取以下错误:</p>
^{pr2}$
<p>在服务器端,一切都是正确的,我得到我需要的任何数据。我以为我需要先解析它,但当我试图解析时,它已经是一个对象了。否则,当我试图从对象<code>TypeError: undefined is not an object</code>中取出某些内容时。在</p>
<p>编辑:有一个打字错误,但问题仍然存在。如果我把它打印到控制台.log公司名称:</p>
<pre><code>console.log(data.notifications);
</code></pre>
<p>什么都没有。但如果我警觉数据.通知:<code>[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]</code></p>
<p>如果我更进一步,像我提到的<code>data.notifications[1].model</code>或{<cd4>}或任何类似{<cd5>}的东西,所有这些理论上都必须是正确的,但是没有返回任何东西。在</p>
<pre><code>TypeError: undefined is not an object (evaluating 'data.notifications.fields.choice_fl')
</code></pre>
<p>编辑2:
还尝试手动设置字段</p>
<pre><code>nots = serializers.serialize('json', Notification.objects.all(), fields=('whom','choice_afl'))
data = {
'notifications': nots
}
return Response(data)
</code></pre>
<p>如果警报<code>alert(data['notifications']);</code>得到这个:</p>
<pre><code>[{"pk": 1, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 2, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 3, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 4, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 5, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {"pk": 6, "fields": {"whom": 1, "choice_afl": "F"}, "model": "blog.notification"}, {
</code></pre>
<p>和之前一样,无论我进一步输入什么,它都是未定义的</p>