使用Javascript

时间:2016-11-25 09:51:28

标签: javascript python ajax flask

我使用带有正在运行的sqlite-db(SQLAlchemy)的flask创建了一个网站。我想发送一个带有javascript的整数到烧瓶并返回。我知道AJAX可以用来实现这一点,但是每当我的javascript游戏中的if / else语句被满足时,我都不知道如何发送整数。

games.html

if (loc == unicornloc) {
    money = 5000;
    alert("\n\nBRAVO! You found the Unicorn! :)");
    }else {
        money = -250;
        alert("The unicorn isn't here :(")
    }

<FORM method="POST" name="searchb">
<input type=checkbox onClick="javascript:search('x1y1');">
<input type=checkbox onClick="javascript:search('x1y2');">
<input type=checkbox onClick="javascript:search('x1y3');">

games.py

@app.route('/games/<money>',methods=['GET'])
@login_required
def games(money):
    print(request.args.get('money', type=int))
    return render_template('games.html',money)

我希望将货币价值计入flask,计算新值,将其传递给我的db并在我的网站上显示更新后的值,而无需重新加载页面。

1 个答案:

答案 0 :(得分:0)

首先在你的html中设置jquery。 确保jquery包含在html页面的head部分中: 如果你在每次单击时发送ajax请求的按钮上放置一个监听器,你就不需要提交表单来更新服务器就足够了:

(0)       Program returned code (0) and output 'Auth-Type = Accept, WISPr-Redirection-URL = http://google.com, Reply-Message = 'hello world''
(0)       control::Auth-Type = Accept
(0)       control::WISPr-Redirection-URL = http://google.com
(0)       control::Reply-Message = hello world

在服务器端,重要的是返回正常http响应的json响应,以完成ajax请求并调用成功或错误URL:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>

var sendServerNotification = function(status){

        var urlToCall = '/games/' + status;
         $.ajax({
            url : urlToCall, // the endpoint
            type : "GET", // http method

    // handle a successful response
    success : function(parentDescriptions) {
        console.log('success'); // log the returned json to the console
        // update the page with jquery

    },

    // handle a non-successful response
    error : function(xhr,errmsg,err) {
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
});

}

    $( document ).ready(function() {
        $('#obsevervedbutton').click(function{
         //we read the value that the user wants to submit: 
         var valueToSubmit = $('#valueToSubmit').val()
         // here you can check if you want to submit the value 
         // or not
         if(true){
            sendServerNotification(valueToSubmit);

         }

         });
    });

    </script>
</head>

<body>
 <button id="obsevervedbutton">notify server</button>
 <input id="valueToSubmit"></input>
</body>

我希望这会让你前进。