Webview数据在Android和HTML页面之间不匹配

时间:2014-07-09 15:11:03

标签: php android jquery webview

我的Android webview中有一个jQuery List View,它从服务器加载数据。我使用HTTP GET响应从服务器数据库获取数据。我在<body onload="loadRes()">中使用它。这是我的方法:

<script>
lastRecord=0;

    function loadRes(){
        $('#sample').html( 'hello' );
        $.get( 
        "queryRestaurantsList.php?lastRecord="+lastRecord,
        function( data ) {
            $('#rest_mesgs').append( data )
            .listview( 'refresh' );
        });
    }
</script> 

但是,我想按特定顺序对此列表进行排序。为此我从Android代码向服务器发送一条POST消息,其中包含一个字符串对象:

String list_order ="0012,0002,0003,0001";

list_order String对象表示数据库中的RestaurantID,它也是主键。此主键的格式为VARCHAR(4)。这是我的php文件: 但是,我总是在我的网页视图上收到“仍在工作”的消息,即使我可以通过HttpResponse看到LogCat中已排序列表的HTML

<?
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");

echo $_POST['ids'];

if($_POST != null){

$query = "SELECT RestaurantID,Name,Short_Loc,Image_Link,Full_Link,Type FROM Restaurant_Info
          ORDER BY FIND_IN_SET(RestaurantID,'".$ids."')";

$result = mysql_query($query) or die( "Unable to execute query");

while ($row = mysql_fetch_array($result)){
        print '<li id="'.$row['RestaurantID'].'" onclick="newAct('.$row['RestaurantID'].')">';   
        print '<a href="'.$row['Full_Link'].'">';
        print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
        print '<h2 style="text-wrap : normal" >'.$row['Name'].'</h2>';
        print '<p id="type" class="ui-li-aside"><strong>'.$row['Type'].'</strong></p>';
        print '<p>'.$row['Short_Loc'].'</p>';
        print '</a>';
        print '</li>';
        }
}
else {
    echo "Still working";
    }

?>

HttpPostID.class - POST数据到服务器的类

public class HttpPostID extends AsyncTask<Void,Integer,Void> {

    static String result;

    private static final String webphp = "http://...../queryRestaurantsList.php";

    String IDs;

    HttpPostID(String ids){
        this.IDs =ids;
    }

    @Override
    protected Void doInBackground(Void... params){

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(webphp);

        try {

            String hello="111,222,333";

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("order",IDs));
            nameValuePairs.add(new BasicNameValuePair("hello",hello));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            result = EntityUtils.toString(resEntity);

            System.out.println(result);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

我在我的Activity中调用它:new HttpPostID(tester).execute(); tester是一个String对象。

LogCat(由于输出很大,只有几行)

07-12 02:25:14.850: I/System.out(10440): <li id="0013" onclick="newAct(0013)"><a href=""><img style="height:80px;" src="http://cedars.hku.hk/sections/campuslife/images/pacific.jpg"><h2 style="text-wrap : normal" >Pacific Coffee Company</h2><p id="type" class="ui-li-aside"><strong>Sandwiches, Cut cakes, Pies, Pastries, Muffins, Premium Ground Coffee, Fruit Juices</strong></p><p>Main Campus</p></a></li><li id="0003" onclick="newAct(0003)"><a href="#page4"><img style="height:80px;" 

3 个答案:

答案 0 :(得分:5)

首先在像这样的HTML中写一个javascript

 <script>
 function reloadRes(var data){
    $('#sample').html( 'hello' );
    $('#rest_mesgs').append( data )
        .listview( 'refresh' );
}
</script>

然后重写Http

public class HttpPostID extends AsyncTask<Void,Integer,String> {

static String result;

private static final String webphp = "http://...../queryRestaurantsList.php";

String IDs;

HttpPostID(String ids){
    this.IDs =ids;
}

@Override
protected String doInBackground(Void... params){

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(webphp);

    try {

        String hello="111,222,333";

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("order",IDs));
        nameValuePairs.add(new BasicNameValuePair("hello",hello));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        result = EntityUtils.toString(resEntity);


        System.out.println(result);
        return result;


    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }


}
    @Override
    protected void onPostExecute(String data){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        webview.evaluateJavascript("javascript:reloadRes(data)",
                null);
    }
    else
    {
        webview.loadUrl("javascript:reloadRes(data)");
    }

    }

}

我是一名Android开发人员,所以我不确定函数reloadRes(var data),请根据您的要求进行修改。

答案 1 :(得分:0)

自从我触及Android开发以来已经有很长一段时间了,所以事情可能已经发生了变化,但我会尝试一下。

webview能够在其中加载的html页面中调用javascript函数。如果你改变你拥有的功能(或为这个特定任务创建一个新的功能),它可以接受参数,你可以在计算距离时从android代码调用该功能。

<script>
lastRecord=0;

    function loadRes(listOrder){
        $('#sample').html( 'hello' );
        $.get( 
        "queryRestaurantsList.php?lastRecord="+lastRecord+"&listOrder="+listOrder,
        function( data ) {
            $('#rest_mesgs').append( data )
            .listview( 'refresh' );
        });
    }
</script>

然后只需更改PHP以反映更改:

echo $_GET['listOrder']; // Test to see if you catch the param

if( isset($_GET['listOrder'],$_GET['lastRecord']) ){

$query = "SELECT RestaurantID,Name,Short_Loc,Image_Link,Full_Link,Type FROM Restaurant_Info
          ORDER BY FIND_IN_SET(RestaurantID,'".$ids."')";
...

希望你能从中得到你需要的东西。祝你好运!

<强> PS!我再说一遍,我对实际的Android内容真的很生气,但是我看到一位评论者留下了一个问题的链接,答案基本上涵盖了相同的方法。

修改

Tibro将问题的Android部分完全覆盖在我眼前。他应该得到赏金,因为我只能用javascript和PHP呈现代码。

答案 2 :(得分:-2)

你的HttpPostID类缺少一个方法。方法doInBackground在后台线程上完成工作。但结果是在onPostExecute方法中收集的。更进一步,我看到你将结果(来自http帖子的响应)分配给静态变量。该值应该从doInBackground方法返回。然后它将作为输入参数传递给onPostExecute方法。因此,您不需要静态变量。

在这里查看第一个示例代码块:http://developer.android.com/reference/android/os/AsyncTask.html。更改您的HttpPostID类以匹配该模型,您应该全部设置。一件事......示例代码从doInBackground返回一个long。该long包含在类声明中,并作为onPostExecute的输入参数。您需要更改为字符串,如下所示:

private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {


String IDs;

HttpPostID(String ids){
    this.IDs =ids;
}
protected String doInBackground(URL... urls) {
    String result = null;
    String webphp = "http://...../queryRestaurantsList.php";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(webphp);

    try {

        String hello="111,222,333";

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("order",IDs));
        nameValuePairs.add(new BasicNameValuePair("hello",hello));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        result = EntityUtils.toString(resEntity);



    } catch (Exception e) {
        e.printStackTrace();
    }
   return result;

 }

 protected void onPostExecute(String result) {
   // this method is executed on the main UI thread
   // result is what is returned from the http post
   String html = result;
 }
 }