[英]Passing a JSON string to django using JQuery and Ajax
我對 Django 有點陌生,並試圖理解它。 目前,我正在創建一個網絡拓撲可視化工具(想想路由器和交換機連接在一起)。 它工作正常,所有數據都保存在一個 javascript 對象中。
我希望能夠在用戶單擊按鈕時將此 javascript 對象發送到 django,以便可以對其進行適當的解析和處理。 我做了很多研究,發現了一堆類似的實現,它們使用 JQuery 和 ajax 的組合來發布 JSON 字符串。 這是我目前的一些代碼:
主應用程序/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')),
url(r'^admin/', admin.site.urls),
]
網絡拓撲/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^json/$', views.returnjson, name='returnjson'),
]
網絡拓撲/views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html')
def returnjson(request):
if request.is_ajax():
request_data = request.POST
print("Raw Data: " + request_data.body)
return HttpResponse("OK")
JavaScript 函數(按下返回 JSON 按鈕):
function returnJsonTop(){
$(document).ready(function() {
$.ajax({
method: 'POST',
url: '/NetworkTopology/json',
dataType: 'json',
data: JSON.stringify(nodes.get(),null,4),
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
});
}
在我的索引模板中,我創建了一個按鈕,該按鈕在按下時調用 returnJsonTop() 函數:
<button id="submitJson" onclick="returnJsonTop();">Deploy</button>
目前,當我按下“部署”按鈕時,我只會收到“它不起作用”的警報,該警報已設置為處理錯誤。 我真的很感激有人在這里指出我正確的方向。 我懷疑問題出在我的 urls.py 文件中,但我嘗試了各種 url 組合但沒有任何運氣。
您正在嘗試根據request.POST
訪問body
。 但 body 是請求的直接屬性。 你的代碼應該是:
request_data = request.body
print("Raw Data: " + request_data)
另請注意,在您的 Javascript 中, $(document).ready
行在那里沒有意義; 你應該刪除它。
首先,您甚至不需要在 ajax 調用中使用所有這些
data: JSON.stringify(nodes.get(),null,4),
替換為
data: nodes.get(),
只要此方法返回有效的 json 對象就足夠了
第二個,我強烈建議你使用一個框架來幫助你解析 JSON
Python 可能有,但為了說明這個例子,我使用了 django rest 框架,這是一個非常好的框架。
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import json
import controllers#this class belongs to my business logic layer, you can encapsulate yours and use instead of it
#in this solution you must create a pre-parser to handle responses
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt # this is for prevent invasions
def login(request):
#this one here handle your jquery post data into a valid json object in python represented by a Dict
envelopin = json.loads(request.body)
# here we pass the dict inside my business controll logic routine which also responds with a valid Python Dict
envelopout = controllers.login(envelopin)
# and for last, we use our pre-parser Class to make your response be handled by jquery as valid json
return JSONResponse(envelopout)
就是這樣,您成功的 jQuery 數據變量將保存信封 json 對象,其形狀與您的 django-python 代碼中的形狀相同。
希望這有幫助
對於那些稍后閱讀本文的人,這就是我所做的:
主應用程序/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
url(r'^admin/', admin.site.urls),
]
網絡拓撲/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^json/$', views.returnjson, name='returnjson'),
]
網絡拓撲/views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
def index(request):
return render_to_response('index.html')
@csrf_exempt
def returnjson(request):
if request.is_ajax():
request_data = request.POST
print("Raw Data: " + str(request_data))
return HttpResponse("OK")
我收到了 403 錯誤,所以我添加了“@csrf_exempt”。 之后我可能會更改它以正確處理它。
返回 JSON 函數:
function returnJsonTop(){
$.ajax({
method: 'POST',
url: '/NetworkTopology/json/',
dataType: 'json',
data: JSON.stringify(nodes.get(),null,4)
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.