我在一家公司實習,我需要使用誰在2012年編程它的另一個學員的程序,所以我做了一些更新,但我有一些問題:XHR無法與Django項目加載
當我按下一個按鈕,我有一個JS,使恢復JSON
。但我有我的Firefox控制檯上的消息:
Object { message: "Unable to load /query/?typeForm=com…", stack:".cache["dojo/errors/create"]/</</[email protected]…", response: Object, status: 0,responseText: "", xhr: XMLHttpRequest }
我的JS:
function queryDataGrid(map, stringForm) {
var test = "pouet";
require(["dojox/grid/DataGrid",
"dojo/store/Memory",
"dojo/data/ObjectStore",
"dojo/_base/xhr",
"dojo/domReady!",
"dojo/dom",
"dojo/_base/array"],
function(DataGrid, Memory, ObjectStore, xhr, arrayUtil, dom) {
var nodeDomGrid = dom.byId("datagrid");
window.alert("hey");
xhr.get({
url: "/query/",
form: dom.byId(stringForm),
handleAs: "json",
load: function(data) {
var nodeDomGrid = dom.byId("datagrid");
var nodeGrid = dijit.byId("datagrid");
var gridLayout = [];
var dataStore = new ObjectStore({ objectStore:new Memory({ data: data.fields }) });
console.log("store");
console.log(data.fields[0][1]);
globalData = data;
for(i in data.columns) {
gridLayout.push({
name: data.columns[i],
field: data.columns[i],
width: "auto"
})
}
nodeGrid.setStructure(gridLayout);
nodeGrid.setStore(dataStore);
var nodeMap = dom.byId("map");
columns = data.columns;
columnsToDisplay = []
numberColumn = 0;
for (i in columns) {
if (columns[i] == "Distance Fin") {
numberColumn = i
}
if (parseInt(i) > parseInt(numberColumn) && numberColumn != 0) {
columnsToDisplay.push({ value: columns[i], label: columns[i]});
}
}
dijit.byId("dataToColor").addOption(columnsToDisplay);
var vectorLayer = map.getLayersByName("KML")[0];
vectorLayer.removeAllFeatures();
var kmlFile = createKMLFile(data.kmldata, dom.byId("hiddenColor").value, dom.byId("sizeLine").value, dom.byId("colourPR").style.backgroundColor, dom.byId("sizePR").value);
var features = KMLToFeatures(kmlFile);
var bounds;
for(var i=0; i<features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectorLayer.addFeatures(features);
console.log(vectorLayer);
map.zoomToExtent(bounds);
refreshLayer(vectorLayer);
if (stringForm == "commonQueriesForm" && dijit.byId("table").get("value") == "location") {
dom.byId("colourPalette").style.display = "block";
dom.byId("styleKML").style.display = "none";
}
else {
dom.byId("colourPalette").style.display = "none";
dom.byId("styleKML").style.display = "block";
}
},
// Message d'erreur à modifier
error: function() {
nodeDomGrid.innerHTML = "La requête a engendré une erreur.";
}
})
});
console.log(stringForm);
};
我的表格:
<form id="commonQueriesForm" data-dojo-type="dijit.form.Form" onload="alert('test')">
<p>
<div id="commonDataTitlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Requêtes'">
<input type="text" name="typeForm" id="typeForm" value="common" style="display:none" />
<select name="table" id="table" class="cSelect" data-dojo-type="dijit/form/Select"
data-dojo-props="onChange:function(){ if (dijit.byId('table').get('value') == 'location') {dijit.byId('age').set('disabled', true); } else {dijit.byId('age').set('disabled', false); }}">
{% for key, value in dictTablesDatabase.items %}
<option value="{{ key }}">{{ key }}</option>
{% endfor %}
<option value="location">Repérages</option>
</select><br />
<select name="road" id="road" class="cSelect" data-dojo-type="dijit.form.Select" data-dojo-props="">
<option value="all">Toutes les routes</option>
{% for road in listRoad %}
<option value="{{ road|first|cut:' ' }}">{{ road|first|cut:' ' }}</option>
{% endfor %}
</select><br />
<select name="age" id="age" class="cSelect" data-dojo-type="dijit.form.Select" data-dojo-props="">
{% for age in arrayNumber %}
<option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>
</div>
<button type="executeButton" data-dojo-type="dijit.form.Button" onClick="queryDataGrid(map, 'commonQueriesForm');">Lancer la requête</button>
</p>
</form>
urls.py:
from django.conf.urls import include, url
from GSRBaseWeb.Home import views as myapp_views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'GSRBaseWeb.views.home', name='home'),
# url(r'^GSRBaseWeb/', include('GSRBaseWeb.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^home/$',myapp_views.home, name='home'),
url(r'^home/query', myapp_views.queryDataGrid, name='queryDataGrid'),
]
意見。 py:
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from GSRBaseWeb.Utils.utils import Utils
from GSRBaseWeb.DataAccess.databaseAccess import DatabaseAccess
from GSRBaseWeb.DataAccess.GSRBaseDLLAccess import GSRBaseDLLAccess
from ctypes import *
# Envoie les données nécessaires aux différents formulaires
def home(request):
dictToSend = {}
data = DatabaseAccess()
dictTablesDatabase = data.dataToDisplay()
dictToSend["dictTablesDatabase"] = dictTablesDatabase
# Sélection de l'ensemble des routes
queryRoads = "SELECT id_route, nom FROM routes"
listRoad = data.executeQuery(queryRoads)
dictToSend["listRoad"] = listRoad
# Liste pour les âges
arrayNumber = []
i = 0
while i < 20:
arrayNumber.append(i)
i += 1
arrayNumber.append("Tous")
dictToSend["arrayNumber"] = arrayNumber
# Liste pour les emplacements
arrayLocation = ["Tous", " ", "D", "C", "G"]
dictToSend["arrayLocation"] = arrayLocation
return render(request, 'Home/home.html', context=dictToSend)
# Récupère le contenu d'un formulaire et le traite en fonction du type de formulaire (commun, simple ou complexe)
def queryDataGrid(request):
# request.GET renvoie un QueryDict (objet Django)
print("YOLO")
parametersContent = request.GET
whatForm = parametersContent.getlist("typeForm")[0]
print(type(whatForm))
try:
accessDLL = GSRBaseDLLAccess()
except:
print(Exception.message())
if whatForm == "common":
table = parametersContent.getlist("table")[0]
road = parametersContent.getlist("road")[0]
if table != "location":
if parametersContent.getlist("age")[0] == "Tous":
age = 20
print("True")
else:
print("False")
age = int(unicode(parametersContent.getlist("age")[0]))
if road == "all":
road = ""
# on fait une requête sur les repérages
if table == "location":
result, number = accessDLL.requete_reperage(road)
else:
result, number = accessDLL.requete_table(table, road, age)
elif whatForm == "simple":
"""
On fait le traitement du formulaire de requêtes simples
Prendre en compte des ajouts des formulaires
On va prendre en compte les différentes lignes du formulaire et leur nombre """
listConditions = []
# Lignes des données
listQueries = dataProcessingForm("Simple", parametersContent)
# Checkout et les routes
conditionCheckout = parametersContent.getlist("conditionCheckout")[0]
conditionRoad = parametersContent.getlist("conditionRoad")[0]
conditionRoad = 'ROUTE()="' + conditionRoad + '"'
listConditions.append(conditionRoad)
# Lignes des conditions
j = 1
while j < 6:
if parametersContent.__contains__("conditionData" + str(j)) == True:
data = parametersContent.getlist("conditionData" + str(j))[0]
# On récupère la table de la condition
table = data.split(":")[0]
location = parametersContent.getlist("conditionLocation" + str(j))[0]
age = parametersContent.getlist("conditionAge" + str(j))[0]
condition = parametersContent.getlist("condition" + str(j))[0]
value = parametersContent.getlist("valueCondition" + str(j))[0]
conditionLine = "(" + data + condition
if (str(value).isdigit()):
conditionLine += str(value)
else:
conditionLine += '"' + str(value) + '"'
conditionLine += ' ET ' + table + ':generation=' + str(age) + ' ET ' + table + ':emplacement="' + location + '")'
if conditionCheckout == "anything":
conditionLine += "NON" + conditionLine
listConditions.append(conditionLine)
else:
break;
j += 1
#@todo modifier la condition pour la Route(), ajouter un ET tout le temps
if conditionCheckout == "atLeast":
conditionQuery = ' OR '.join(listConditions)
elif conditionCheckout == "all":
conditionQuery = ' ET '.join(listConditions)
result, number = accessDLL.requete_avancee(listQueries, conditionQuery)
elif whatForm == "complex":
# On fait le traitement du formulaire de requêtes complexes
listQueries = dataProcessingForm("Complex", parametersContent)
conditionQuery = parametersContent.getlist("textareaConditions")[0]
result, number = accessDLL.requete_avancee(listQueries, conditionQuery)
json = ""
if number[0] > 0:
# json à renvoyer en fonction des données des formulaires
listResult = []
i = 0
while i <= number[0]:
listResult.append(result[i])
i += 1
json = Utils.jsonSerializeQueryResult(listResult)
print(json)
return HttpResponse(content=json,
status=200,
mimetype="text/plain")
def dataProcessingForm(form, parametersContent):
""" Mise en forme des données des formulaires pour les requêtes
La mise en forme est faite pour la DLL utilisée qui effectue le plus gros des requêtes
"""
listQueries = []
i = 1
while i < 6:
if parametersContent.__contains__("data" + form + str(i)) == True:
data = parametersContent.getlist("data" + form + str(i))[0]
location = parametersContent.getlist("location" + form + str(i))[0]
if parametersContent.getlist("age" + form + str(i))[0] == "Tous":
age = 20
else:
age = int(unicode(parametersContent.getlist("age" + form + str(i))[0]))
contentToAdd = data + "," + location + "," + str(age)
print(contentToAdd)
listQueries.append(contentToAdd)
else:
break;
i += 1
return ";".join(listQueries)
在標題中指出這是一個Django項目將更有可能引起您的注意,導致可能的答案。 –
您應該首先從您提供的JSON中展開消息。 例如無法加載/查詢/?typeForm = com ... – garmoncheg
準確地說,我不知道如何顯示隱藏的內容。 – Nitner