Ajax发布到Python服务器:没有JSON对象可以被解码

时间:2017-08-31 22:08:52

标签: python json

我收到此错误:

来自服务器的

function ipTrackButton(){ if(window.jQuery){ var $ = jQuery; var phonenumber = '+31 (0)20 - 679 62 22', holder = $('#text-5 > .textwidget'), newHTML = 'T: <span id="ipCallButton">Bel ons | Call us</span><br>E: <a href="mailto:info@pvhadvocaten.nl">info@pvhadvocaten.nl</a>', body = $('body'); //Inject styles var style = '#ipCallButton { background-color:#eaeaea;padding:5px 8px;cursor:pointer;text-decoration:underline; } #ipCallButton.ipClicked { text-decoration:none;cursor:default; } '; body.append('<style>'+style+'</style>'); //Set new content holder.html(newHTML); //Set event body.on('click', '#ipCallButton:not(.ipClicked)', function(){ var _this = $(this); _this.html(phonenumber); _this.addClass('ipClicked'); //Send event ga('send', 'event', 'Contact', 'Click', 'Telefoonnummer'); }); } else { setTimeout(ipTrackButton, 50); } } ipTrackButton();

这是来自客户端的ajax请求

ValueError: No JSON object could be decoded

服务器代码:

        function searchDB(profile_url) {
            console.log(profile_url);
            $.ajax({
                type: 'POST',
                url:'http://127.0.0.1:5000/update_greenhouse',
                data: JSON.stringify(profile_url),
                contentType: "application/json"
            })
        }

我将@app.route('/update_greenhouse', methods=['GET', 'POST', 'OPTIONS']) def update_gh(): y = request.data print(y) json.loads(y) 设置为json。为什么服务器会给我这个错误?

2 个答案:

答案 0 :(得分:0)

您似乎没有向服务器发送正确的JSON。仅设置contentType是不够的。您的数据(profile_url)需要作为JSON对象正确编码。

在您的请求代码中尝试类似的内容:

data: JSON.stringify({'url': profile_url})

然后,您的服务器将获得一个基本词典。如果你真的想要传递一个字符串,你可以放弃服务器上的json.loads()并从request.data操作方向,但是为了构建除了hello world应用之外的任何东西,我强烈建议使用更像JSON的结构化格式。

您还需要为每个Flask请求返回响应(或错误)。如果您正在构建基于JSON的API,我建议使用Flask的jsonify

的内容
return flask.jsonify({'status': 'updated'})

成功,可能有关于更新状态的详细信息。如果有错误,您应该返回带有正确错误代码的响应,如下所示:

return flask.make_response(jsonify({'error': 'Error details'}), 418)

用适当的HTTP error code取代418

答案 1 :(得分:0)

我不知道为什么,但"OPTIONS"中的methods=[]导致了这个问题。删除它,一切正常。