我的想法是我将带有ajax的数据发送到我的类视图,当类视图接收到将数据发送到外部服务器的数据时,这个服务器给我一个响应,我通过成功函数在模板视图中显示在我的ajax post方法中。它工作得很棒,完全没问题。
但是,当我的视图获得POST请求时,它还会通过模块在我的DataBase中创建一些数据(它用于搜索历史记录)。我保存这些数据,然后我想获取所有这些数据并显示它。
所以,我需要的是返回两组数据,一个是json用于我的ajax方法的成功函数,另一个用于我的数据库。我不知道如何将它们放在一起,或者如何将它们分开发送......有什么想法吗?
查看课程
user_id = request.session['user_id']
jresponse = response.json()
query = QueryHistory(userID = user_id, queryID = jresponse['query'], query = keyword)
query.save()
query_list = QueryHistory.objects.all()
return HttpResponse(json.dumps(jresponse), content_type="application/json")
saerch.js
success : function(response) {
$('#id_keyword').val(''); // remove the value from the input
console.log(response); // log the returned json to the console
if(response.hasOwnProperty('results')){
for (var i = 0; i < response.results.length; i++){
$("#search-table").append("<tr><td>alldatagoeshere</td></tr>");
}
}
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
模型
class QueryHistory(models.Model) :
userID = models.CharField(max_length=100)
queryID = models.CharField(max_length=100)
query = models.CharField(max_length=100)
date = models.DateTimeField(auto_now_add=True, blank=True)
从我的视图类中可以看到,有两个不同的数据集jresponse
(来自外部服务器工作正常)和query_list
来自我自己的数据库(应该添加到{ {1}})