简体   繁体   中英

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]. How can i convert data return to js object. here is my code

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

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. Django offers some convenience for that with the JsonResponse [Django-doc] :

from django.http import 

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 (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 .

It is typically better to just pass a dictionary (so no list), and then the safe=False parameter can be removed. 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.

At the JavaScript side, you then only need to parse the JSON blob to a JavaScript object:

//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) {
        
        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM