【问题标题】:Running JavaScript in WebView with LoadData after getting data from post request从发布请求中获取数据后,使用 LoadData 在 WebView 中运行 JavaScript
【发布时间】:2014-10-12 09:32:02
【问题描述】:

在通过 post 请求获取字符串形式的 html 后,我想在 webview 中使用 webview 的 loadData 方法在 android 中运行 javascript。这是我的代码。我搜索了很多链接,但没有一个符合我的情况。有什么帮助吗?

public class MainActivity extends ActionBarActivity {

    WebView wv;
    String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         

         wv=(WebView)findViewById(R.id.webView1);
         Thread t= new Thread(new Runnable() {  
            @Override
            public void run() {
                // TODO Auto-generated method stub
                postData();
            }

        });
        t.start();
        while(t.isAlive());
        wv.getSettings().setJavaScriptEnabled(true);
        wv.loadData(result, "text/html", null);


    }
    public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://result.abc.com/Home1/R2");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
        nameValuePairs.add(new BasicNameValuePair("value1", "5001"));
        nameValuePairs.add(new BasicNameValuePair("value2", "201214"));
        nameValuePairs.add(new BasicNameValuePair("value3", "212"));
        nameValuePairs.add(new BasicNameValuePair("value4", "ABC"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        result = EntityUtils.toString(response.getEntity());


    } catch (ClientProtocolException e) {           
        // TODO Auto-generated catch block
    } catch (IOException e) {                       
        // TODO Auto-generated catch block
    }
    }


}

【问题讨论】:

    标签: javascript android android-webview


    【解决方案1】:

    你在得到post请求的结果后放置这两行代码。

     wv.getSettings().setJavaScriptEnabled(true);
     wv.loadData(result, "text/html", null);
    

    result = EntityUtils.toString(response.getEntity());之后 所以,最终代码看起来像这样::

    result = EntityUtils.toString(response.getEntity());
    wv.getSettings().setJavaScriptEnabled(true);
    wv.loadData(result, "text/html", null);
    

    【讨论】:

    • 这两行是线程完成任务后已经写好的。如果您在另一个线程(即 webView.load(...))中编写 webview 的加载任务,那么您将得到一个运行时异常。 "所有的 webview 方法必须在同一个线程上调用"
    • 也试试这个 wv.loadData(result, "text/html; charset=UTF-8", null);
    • 为什么你明白javascript没有运行。
    • 当我通过 post 请求获取 Html 时。它包含一些功能,并在带有 onload 的 body 标记中调用。这没有运行。我必须运行它。
    • 而不是run(),你为什么不试试asynctask?因为您面临“所有 webveiw 方法都应该在同一个线程上调用”?
    猜你喜欢
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多