客户端发布响应中的jQuery错误-POST HTTP / 1.1“ 400

时间:2019-10-16 08:20:50

标签: javascript jquery ajax flask flask-restful

我无法弄清楚我的代码出了什么问题,并且我对jQuery不太满意。 我正在尝试建立将保存汽车数据的HTML表单。它基于以下形式:

enter image description here

HTML源代码is here

在单击按钮后将表单数据发送回程序。

我使用级联的制造商(代码中的proizvodjac)和基于this code的汽车模型下拉列表升级了该表格。但这不起作用。

我一直收到HTTP 400,这意味着来自客户端的POST调用格式错误。

这是我的jQuery函数:

$(function () {

        var carsdata = {"alfaromeo":["mito","156","147","giulietta","159","166","146"],"audi":["a3","a4","a6","a5","80","a1","q3","a8","q5"],"bmw":["320","116","x3","316","318","118","530","x1","520","x5","525","330","120","323","serija 1"],"chevrolet":["spark","lacetti","captiva","aveo","cruze"],"citroen":["c4","c4 grand picasso","c3","c5","c4 picasso","xsara","berlingo","c2","xsara picasso","saxo","ds5","c1"],"fiat":["brava","bravo","panda","grande punto","stilo","punto","punto evo","doblo","500","tipo","uno","coupe"],"ford":["c-max","fiesta","focus","mondeo","fusion","ka","escort"],"honda":["civic","accord","cr-v"],"hyundai":["getz","i10","i20","atos","i30","coupe","elantra","accent","santa fe","ix35","tucson"],"kia":["rio","pro_cee'd","sportage","cee'd","pride","sorento"],"mazda":["3","2","323 f","626","6","cx-5","323","premacy","5"],"mercedes":["a-klasa","c-klasa","e-klasa","b-klasa","124"],"mercedes-benz":["e-klasa","clk-klasa","c-klasa","s-klasa","190","a-klasa","b-klasa","c t-model","ml-klasa","w 124","124"],"nissan":["qashqai","x-trail","note","primera","micra","juke","almera"],"opel":["corsa","astra","zafira","meriva","vectra","insignia","mokka","tigra","combo","astra gtc","kadett"],"peugeot":["308","207","206","306","106","307","208","406","508","407","partner","3008","405"],"renault":["thalia","clio","scenic","grand scenic","kangoo","captur","megane grandtour","megane","laguna","5","megane break","twingo","modus","kadjar","megane classic","espace","megane scenic","megane coupe","megane sedan"],"seat":["toledo","leon","ibiza","altea","cordoba"],"skoda":["fabia","octavia","120","superb","felicia","rapid"],"smart":["fortwo"],"toyota":["corolla","yaris","auris","avensis","rav 4","land cruiser"],"vw":["polo","golf v","golf iv","golf vii","passat","golf vi","jetta","passat variant","caddy","sharan","tiguan","golf variant","golf ii","vento","golfplus","golf iii","bora","touran","touareg","up!"]};

        var proizvodjac = $('<select id="proizvodjac"></select>');
        var model = $('<select id="model"> </select>');
        $.each(carsdata, function(item, key) {
            proizvodjac.append('<option >' + item + '</option>');
        });
        $("#containerProizModel").html(proizvodjac);
        $("#proizvodjac").on("change", function(e) {
            var item;
            var selected = $(this).val();
            if (selected === "alfaromeo") {
                item = carsdata[selected];
                } else {
                item = carsdata[selected];
            }
            $(model).html('');
            $.each(item, function(item, key) {
            model.append('<option >' + key + '</option>');
                });
            });

            $("#containerProizModel").append(model);

        $("button#predict").click(function(e){
            e.preventDefault();
            /*Get for variabes*/
            var kilometraza = $("#kilometraza").val(), godina_proizvodnje = $("#godina_proizvodnje").val();
            var snaga_motora = $("#snaga_motora").val(), vrsta_goriva = $("#vrsta_goriva").val();           

            /*create the JSON object*/
            var data = {"kilometraza":kilometraza, "godina_proizvodnje":godina_proizvodnje, "proizvodjac":proizvodjac, "model":model, "snaga_motora":snaga_motora, "vrsta_goriva":vrsta_goriva}
            /*send the ajax request*/
            $.ajax({
                method : "POST",
                url : window.location.href + 'api',
                data : $('form').serialize(),
                success : function(result){
                    var json_result = JSON.parse(result);
                    var price = json_result['price'];
                    swal('Predviđena cijena auta je '+price+' kn', '','success')
                },
                error : function(){
                    console.log("error")
                }
            })
        })
        })

注释和解释在代码中。

在服务器端:

服务器需要user_input字典,该字典是根据POST请求返回的变量构建的。 API方法的外观如下:

@app.route('/api',methods=['POST'])
def get_delay():
    result=request.form
    proizvodjac = result['proizvodjac']
    model = result['model']
    godina_proizvodnje = result['godina_proizvodnje']
    snaga_motora = result['snaga_motora']
    vrsta_goriva = result['vrsta_goriva']
    kilometraza = result['kilometraza']


    user_input = {'proizvodjac':proizvodjac, 
                  'model':model,
                  'godina_proizvodnje':godina_proizvodnje,
                  'snaga_motora':snaga_motora, 
                  'vrsta_goriva':vrsta_goriva, 
                  'kilometraza':kilometraza
             }

    print(user_input)    
    a = input_to_one_hot(result)
    price_pred = gbr.predict([a])[0]
    price_pred = round(price_pred, 2)
    return json.dumps({'price':price_pred});

Google Chrome开发者控制台错误:

enter image description here

它指向: enter image description here

编辑1:

我不知道如何将proizvodjac和模型传递给onClick函数。查看断点发生的情况: enter image description here

“网络”标签上的XHR:

enter image description here

正在用数据填充HTML表单,确定只有制造商和模型不会传递给onClick:

enter image description here

编辑2: 越来越接近解决方案。我添加了:

var proizvodjac = $("#proizvodjac").val()
                var model = $("#model").val()

根据建议,现在所有变量都已成功传递! 但是我仍然收到错误400,因为最终的ajax POST调用被卡在某处。

enter image description here

编辑3: 更改为

data : $('form').serialize()

data = data 

AJAX方法一切正常:

enter image description here

仍然无法正常工作。

1 个答案:

答案 0 :(得分:1)

这里有两个主要问题:

1)您没有从两个字段中正确获取值。您需要添加

var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()

$("button#predict").click(function(e){函数内部。

2)您正在收集所有这些值,并将它们放入data变量中……但是您什么也没做。关于要发送哪些数据,您的AJAX请求配置如下:

data : $('form').serialize()

serialize()函数会自动从<form>标签内的字段中获取所有原始数据。在您的方案中,如果您想根据data对象发送一组自定义数据(而不只是表单的原样内容),则只需将其更改为

data: data

因此它改为在POST请求中从该对象发送信息。