2014-07-09 3 views
3

서버에서 데이터를로드하는 Android webview에 jQuery List View가 있습니다. HTTP GET 응답을 사용하여 서버 데이터베이스에서 데이터를 가져옵니다. 나는 이것을 <body onload="loadRes()">에서 사용한다. 이것은 나의 방법입니다 :안드로이드와 HTML 사이의 Webview 데이터 불일치 페이지

<script> 
lastRecord=0; 

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

그러나이 목록을 특정 순서로 정렬하고 싶습니다. 이를 위해 나는이 같은 문자열 개체를 포함하는 서버에 안드로이드 코드에서 POST 메시지를 보내

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

list_order String 객체는 기본 키 데이터베이스에 RestaurantID을 나타냅니다. 이 기본 키의 형식은 VARCHAR(4)입니다. 클래스 - HttpResponse에

<? 
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하지만 내가 로그 캣의 정렬 된 목록의 HTML을 볼 수 있지만 난 항상 내 웹보기에 "여전히 작동"라는 메시지를 얻을 그러나이 내 PHP 파일입니다 서버에이 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; 
    } 
} 

내 활동이 전화 : new HttpPostID(tester).execute();tester는 String 객체이다.

로그 캣 (단 몇 줄의 출력이 크기 때문에는)

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

먼저 GET을 통해 데이터를 가져온 다음 POST를 통해 같은 데이터를 보내서 정렬 할 것을 의미합니까? – MTahir

+0

@MTahir. 그렇습니다.하지만 채널은 다릅니다. PHP 코드에 POST 요청을 보내고 있습니다. 웹 페이지는 GET 요청에서 해당 PHP 파일을 읽습니다. – stud91

+0

정렬 된 결과를 첫 번째로 반환하거나 앱에서 jQuery를 사용하여 결과를 반환 할 수 있습니다. 예를 들어 [http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery]를 참조하십시오. – MTahir

답변

5

는 처음에는 그런 다음 다시이

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

같은 HTML에서 자바 스크립트를 쓰기 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)"); 
    } 

    } 

}

내가 안드로이드 개발자입니다, 그래서이 기능에 대한 확실하지 않다 reloadRes (var 데이터), 요구 사항에 따라 수정하십시오.

+0

+1에있는'$ .get'에 의해 막히지 않아서 좋은 Android 픽스와 사전/사후 kitkat 확인을 제공하지 않는 이유입니다. 웨이는 PHP와 JS의 대답보다 도움이된다. – Canis

-2

귀하의 HttpPostID 클래스는 방법이 없습니다. 메소드 doInBackground는 백그라운드 스레드에서 작업을 수행합니다. 그러나 결과는 onPostExecute 메서드에서 수집됩니다. 더 나아가 결과 (http 포스트의 응답)를 정적 변수에 할당하는 것을 볼 수 있습니다. 이 값은 doInBackground 메서드에서 반환되어야합니다. 그런 다음 onPostExecute 메소드에 입력 매개 변수로 전달됩니다. 결과적으로 정적 변수는 필요하지 않습니다.

샘플 코드의 첫 번째 블록을 여기에서보십시오 : http://developer.android.com/reference/android/os/AsyncTask.html. 해당 모델과 일치하도록 HttpPostID 클래스를 변경하면 모든 설정이 이루어져야합니다. 한 가지 .... 샘플 코드는 doInBackground에서 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; 
} 
} 
+0

나는 이미 내 http 게시물의 응답을 잡기 중이다. 내 질문에 LogCat 덤프를 참조하십시오. 내 문제는 왜이 응답이 자바 스크립트 – stud91

0

그것은 오래되었습니다,하지만 나는 그것을 시도주지 :이 같은 문자열로 변경해야합니다.

webview에는 내부에로드 된 html 페이지에서 javascript 함수를 호출하는 기능이 있습니다. 매개 변수를 받아 들일 수있는 방식으로 가지고있는 함수를 변경하거나이 특정 태스크에 대해 새 함수를 만들면 거리를 계산할 때 안드로이드 코드에서 해당 함수를 호출 할 수 있습니다.

<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 완벽하게 내 눈에 질문의 안드로이드 부분에 덮여있다. 그는 단지 자바 스크립트와 PHP로 코드를 표시 할 수 있었기 때문에 현상금을 받아야합니다.