jquery - Django:如何在jquery中访问JsonResponse字典?

标签 jquery json django

Jquery

$('#id_buysell').on('change', function(){

            console.log("buysell");

            var $id_buysell = $('#id_buysell').val();
            console.log($id_buysell);

            $.ajax({
                method: "GET",
                url: "/myportfolio/add_transaction",
                data: { buysell: $id_buysell }
            });

        });

浏览次数

def add_transaction(request):

    if request.method == "GET":
        if request.is_ajax():
            print("ajax test")

            #print(request.GET.get)
            print(request.GET.get('coin'))
            print(request.GET.get('buysell'))


            data = {
                'view_buysell': request.GET.get('buysell'),
                'view_coin': request.GET.get('coin')
            }

            form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)

            return JsonResponse(data)

如何访问从 View 中的 JsonResponse(data) 发送到我的 jquery 文件的字典?总的来说,我对 jquery 和前端开发的了解有限。我知道这将通过 JSON 编码的响应发送,但在搜索时无法找到正确的答案。

最佳答案

您使用 $.ajax(..) 执行 AJAX 请求,但您从未指定请求成功时要执行的操作以及应如何处理数据。

传递给 $.ajax(..) 调用的对象可以包含一个 success 键,该键应包含一个通过响应调用的函数:

$.ajax({
    method: "GET",
    url: "/myportfolio/add_transaction",
    <b>dataType: 'json',</b>
    <b>success: function(data, status) {
        // do something with data and status
    },</b>
    data: { buysell: $id_buysell }
});

data 因此包含响应中包装的数据,status 包含响应的状态代码。

您还可以添加一个 error 键:响应返回错误时调用的函数:

$.ajax({
    method: "GET",
    url: "/myportfolio/add_transaction",
    dataType: 'json',
    success: function(data, status) {
        // do something with data and status
    },
    <b>error: function(response) {
        // do something in case the request returns an error
        // for example alert the user that the buy/sell transaction failed
        // (by checking response.status, response.responseText, etc.)
    },</b>
    data: { buysell: $id_buysell }
});

关于jquery - Django:如何在jquery中访问JsonResponse字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50509898/

相关文章:

python - 为什么在运行 Locust 时出现 403 错误?

javascript - 从数组向对象添加值,并且当数组用完时不会变得未定义

json - 使用 ClickHouse 使用来自 Kafka 的嵌套 JSON 消息

ajax - 将POST与core-ajax-dart结合使用时无法将JSON数据发送到服务器REST API

javascript - 解析js中没有 `eval`的数据

python - 使用gunicorn运行app报错

django - 基于性能的 Websockets VS 服务器发送事件(SSE)

javascript - 谷歌地图信息窗口无法正确显示,但当我打开 firbug 时,它运行良好

jquery 删除悬停时添加类

jquery - 滚动到列表中的某个项目