【问题标题】:How to get rating star value from mysql?如何从 mysql 中获取评分星值?
【发布时间】:2014-12-12 18:27:29
【问题描述】:

在我的基于 Worklight 的应用程序中,我在 mysql 中存储了一个评级值 (int)。我有作为 JSON 数据的评级整数值。

{"storeId":1000,"zipcode":"600014","rating":3,}

使用 Jquery,我需要在应用程序中将该评分值显示为星星的图像。 如果值为 2,则需要显示 2 颗星图,以此类推。

我怎样才能做到这一点?

【问题讨论】:

  • 基本上你想问如何阅读这个JSON响应,对吧??

标签: javascript ibm-mobilefirst worklight-adapters


【解决方案1】:

看看到目前为止您已经实现了什么(适配器实现、客户端适配器调用......)会很有帮助。
没有它,我只能提供一种可能的方法来从数据库中获取值并显示它。

假设:

实施:

  1. 在 common\index.html 中,例如,有一个空的 UL 元素,以便获取的数据将在一个列表中:

        <ul id="usersAndStars"></ul>
    
  2. 在 common\js\main.js 中,你调用你的适配器:

    // Of course, you can invoke it whenever you actually want to, and not like below...
    function wlCommonInit(){
        getStarsFromDatabase();
    }
    
    function getStarsFromDatabase() {
        var invocationData = {
            adapter: 'getStars',
            procedure: 'getStars'
        };
    
        WL.Client.invokeProcedure(
            invocationData,
            {
                onSuccess: displayStars,
                onFailure: failedGettingStars
            });
    }
    
  3. 然后你处理调用的响应,失败和成功:

    function failedGettingStars() {
        alert("failure");
    }
    
    function displayStars(response) {
        var ul = $('#usersAndStars'); 
        var i, j, li;
    
        for (i = 0; i < response.invocationResult.resultSet.length; i += 1) {     
            // Create new <li> element and populate it
            li = $("<li/>").text("Item " + [i+1] + " has " + response.invocationResult.resultSet[i].stars + " stars: ");
    
            // Add images of a star
            // Note that this is purely applicative - instead of adding several img tags,
            // You could simply add an image showing 5 or 2 or 3 or however stars you want...
            // Or in any other way you want.
            for (j = 0; j < response.invocationResult.resultSet[i].stars; j += 1) {
                li.append("<img src='images/\star.png' alt='star'/>");
            }
    
            // Append the <li> element to the <ul> element
            ul.append(li);
        };
    }
    
  4. 在 adapters\getStars\getStars-impl.js 文件中:

    var selectStatement = WL.Server.createSQLStatement("select * from users");
    
    function getStars() {    
        return WL.Server.invokeSQLStatement({
            preparedStatement : selectStatement,
            parameters : []
        });
    }
    
  5. 在 adapters\getStars\getStars.xml 文件中:

    ...
    ...
    ...
    <procedure name="getStars"/>
    

最终结果:

【讨论】:

  • 我会使用带有 CSS 的单个类(星号为 background-image),因此您可以只将一个元素插入 DOM 并使用 CSS/JavaScript 更改其宽度以显示所有星号。这也节省了 HTTP 请求。
  • 是的,我同意。然而,正如代码 sn-ps 中所指出的,星星的显示可以大大优化。但这不是问题所在;用户真正想知道的是如何处理 Worklight 适配器调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多