【问题标题】:Webview Data Mismatch between Android and HTML pageAndroid 和 HTML 页面之间的 Webview 数据不匹配
【发布时间】:2014-08-30 16:44:21
【问题描述】:

我的 Android 网页视图中有一个 jQuery 列表视图,可以从服务器加载数据。我使用 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,我也总是在我的 Web 视图中收到消息“仍在工作”

<?
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 - 将数据发布到服务器的类

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 是一个字符串对象。

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;" 

【问题讨论】:

  • 您的意思是首先您通过 GET 获取数据,然后通过 POST 将相同的数据发送到排序?
  • @MTahir。是的,你可以说,但渠道不同。我正在从应用程序代码向 php 文件发送 POST 请求。网页从 GET 请求中读取该 php 文件
  • 您可以首先返回排序结果,也可以在您的应用程序中使用 jQuery。例如,参见 [stackoverflow.com/questions/1134976/…
  • @MTahir 实际上,我正在尝试根据距离我最近的地方对这个列表进行排序。这就是我使用该应用程序向服务器发送 POST 消息以便它可以创建此列表的原因。 $_POST['ids'] 包含按最近位置排列的餐厅 ID
  • 每当发送 POST 消息时,我只需要一些东西来加载 HTML 中的列表。我能够在 LogCat 中显示的响应中捕捉到这一点,它向我显示了排序列表的 HTML。但是这不会出现在 webview 中

标签: php android jquery webview


【解决方案1】:

首先像这样在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 用于出色的 Android 修复并提供前/后奇巧检查。比我的 PHP 和 JS 答案更有帮助。
【解决方案2】:

我已经很久没有接触 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 呈现代码。

【讨论】:

    【解决方案3】:

    您的 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;
     }
     }
    

    【讨论】:

    • 我已经收到了我的 http 帖子的响应。请参阅我的问题中的 LogCat 转储。我的问题是为什么javascript中的$.get没有捕捉到这个响应
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多