[英]Django/Ajax/Javasdript JSON.parse convert string to JavaScript object
I am using Ajax to to send a get request from the sever, i am querying and getting a particular product from the product model, i want to return result as JavaScript objects but its return this '{' as i try to access the first value from the responseText[0]. 我正在使用Ajax从服务器发送获取请求,我正在从产品模型中查询并获取特定产品,我想以JavaScript对象的形式返回结果,但是当我尝试访问第一个值时它返回此'{'来自responseText [0]。 How can i convert data return to js object.
我如何将返回的数据转换为js对象。 here is my code
这是我的代码
views.py views.py
def edit_product(request):
product_id = request.GET.get('product_id')
print('THIS IS PRODUCT ID ', product_id)
product = Product.objects.get(pk=product_id)
data = [
{
'name':product.name,
'brand':product.brand,
'price':product.price,
'description':product.description
}
]
return HttpResponse(data)
ajax.js ajax.js
function getProductEditId(product_id){
//alert(id)
document.getElementById('gridSystemModalLabel').innerHTML='<b> Edit product </b>';
//change modal header from Add product to Edit product
var request = new XMLHttpRequest();
request.open('GET', '/edit_product/?product_id=' + product_id, true);
request.onload = function(){
console.log('hello world', product_id)
//var data = request.responseText
var data = JSON.parse(JSON.stringify(request.responseText));
console.log(data[0])
}
request.send();
}
A HTTP response can not contain a dictionary, you can pass data through a specific format, like for example JSON. HTTP响应不能包含字典,您可以通过特定格式(例如JSON)传递数据。 Django offers some convenience for that with the
JsonResponse
[Django-doc] : Django通过
JsonResponse
[Django-doc]提供了一些便利:
from django.http import
JsonResponse
def edit_product(request):
product_id = request.GET.get('product_id')
print('THIS IS PRODUCT ID ', product_id)
product = Product.objects.get(pk=product_id)
data = [
{
'name':product.name,
'brand':product.brand,
'price':product.price,
'description':product.description
}
]
return
JsonResponse(data, safe=False)
But as the code hints, this is not safe, since an array at the root level was a famous JSON hijacking exploit . 但是如代码所示,这并不安全,因为根级别的数组是著名的JSON劫持漏洞 。
It is typically better to just pass a dictionary (so no list), and then the safe=False
parameter can be removed. 通常最好只传递一个字典(这样就没有列表),然后可以删除
safe=False
参数。 Although it is not really "safe" to then just assume that all security exploits are gone. 尽管然后假设所有安全漏洞已荡然无存并不是真正的“安全”。
Alternatively, you can use json.dumps
[Python-doc] (which is more or less what JsonResponse
does internally), but then you thus will probably end with duplicate code. 另外,您可以使用
json.dumps
[Python-doc] (这或多或少是JsonResponse
在内部执行的操作),但是这样您可能会以重复的代码结尾。
At the JavaScript side, you then only need to parse the JSON blob to a JavaScript object: 在JavaScript端,您只需要将JSON Blob 解析为JavaScript对象:
//change modal header from Add product to Edit product
var request = new XMLHttpRequest();
request.open('GET', '/edit_product/?product_id=' + product_id, true);
request.onreadystatechange = function() {
console.log('hello world', product_id)
if(this.status == 200 && this.readyState == 4) {
var data = JSON.parse(this.responseText);
console.log(data[0])
}
}
It is also not very clear to me why you encapsulate the data in a list here: if the response always contains one element, it makes more sense to just pass the dictionary. 我也不十分清楚为什么要将数据封装在此处的列表中:如果响应始终包含一个元素,则仅通过字典就更有意义了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.