如何对按钮单击做出反应以更改地图中的参数?

How to react to a button click in order to change a parameter in a map?

我正在使用 playframework 2.3.8,我正在尝试实现某种类似 Stack Overflow 的投票系统。到目前为止,我在地图中有一些问题/答案,我将其发送到视图。按钮在那里,但我不知道如何让它们对点击做出反应以更改得分(arrowUp 应该对计数器投赞成票,arrowDown 类似)。

这是一个示例图片:

这是我的控制器Application.java:

static Map<Question, List<Answer>> myMap = new HashMap<Question, List<Answer>>();

public static void initialize() {
        // Question format: ID / questionText / voteScore / userID
        // Answer format: ID / questionID (answer linked to question) / answerText / voteScore / userID
        Question question1 = new Question("xyz", "Do Androids dream?", 127, "Marcus");
        Answer answer11 = new Answer("zab", "xyz", "Only of electric sheep!", 70, "Tibor");
        Answer answer12 = new Answer("qwert", "xyz", "No, they dont!", 10, "Sarah");

        List<Answer> answerList1 = new ArrayList<Answer>();
        answerList1.add(answer11);
        answerList1.add(answer12);

        myMap.clear();
        myMap.put(question1, answerList1);
}

    public static Result index() {
        initialize();
        return ok(views.html.index.render(myMap));
    }

这是我的 视图 class (index.scala.html):

@import model.Question
@import model.Answer

@(myMap: Map[Question, List[Answer]])

@main("Main") {
@for((question, value) <- myMap){
(some HTML to make it look nice)
<button type="button" class="btn btn-default"  onclick="voteUp()" id="upvoteButton" 
   value="voteUp" style="width: 30px; height: 30px; text-align: center; vertical-align: center;">
            <span class="glyphicon glyphicon-arrow-up" aria-hidden="true" style="color:orange"></span>
</button>
@question.voteScore
(some HTML to make it look even nicer)
}

我的routes.conf:

GET     /                           controllers.Application.index()
GET     /                           controllers.Application.upVote()
GET     /Forum                      controllers.Forum.askQuestion()
GET     /Einstellungen              controllers.Application.showSettings()
GET     /Quiz                       controllers.Application.startQuiz()

我不知道我是否可以通过控制器 class 在路线上使用按钮,因为大多数其他项目似乎都使用 Javascript。那么如何捕捉按钮点击并更新 voteScore?

[EDIT1]:我现在添加了一个脚本,它只增加第一个问题的投票分数。

<script language="javascript"> 
    function voteUp() {
        var num = $('#num');
        var currentNumber = num.text().length ? parseInt(num.text()) : 0;
        num.text(currentNumber + 1);
    }
</script>

在我的 index.scala.html 中,我向 @question.voteScore:

添加了一个 span-tag
<span id="num"> @question.voteScore </span>

但是当我遍历地图时,我只能更改第一个问题的值。第一个 upvote 按钮有效,而所有其他按钮也增加了第一个问题的 voteScore!

那么如何从地图中获取每个相应问题的相应值,更改它并将其放回地图中?

首先您需要做的是捕捉该按钮上的点击事件。使用 jquery,使用 class 或 id 将事件监听器添加到特定按钮。

其次 你需要在事件监听器中进行 AJAX 调用,这将触发 API 并且 onSuccess 在 UI 中增加使用 jquery 函数,如果出现错误,显示从 API.

收到的错误消息

Third在POST的Play中创建一个API或GET任何你想要的,这个API将在AJAX 来自 UI。您需要为问题和答案投票创建不同的 API。在两个 API 中都将 id 作为参数并递增 DB 中的值,然后 return 递增的值。如果有任何错误或错误参数发送错误消息,statusCode > 300.