首页 > 解决方案 > Xamarin Android jQuery AJAX 在发布模式下不起作用

问题描述

我在 Xamarin 中有一个适用于 Android 的应用程序。我的 WebView 中有一个 HTML 页面,我使用 AJAX 进行请求。在调试模式下它可以完美运行,但在发布模式下它会出错。

$.ajax({
   type: "POST",
   url: 'http://****.com',
   data: data,
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function(data, status) {
      alert('success')
   },
   error: function(xmlRequest) {
      alert('error')
   }
});

这是我的网络视图代码:

 WebView app_view = null;
 WebSettings app_web_settings = null;


protected override void OnCreate(Bundle savedInstanceState)
{
   base.OnCreate(savedInstanceState);
   // Set our view from the "main" layout resource
   SetContentView(Resource.Layout.Main);

   app_view = FindViewById(Resource.Id.webViewApp) as WebView;
   app_web_settings = app_view.Settings;
   app_web_settings.JavaScriptEnabled = true;
   app_web_settings.AllowUniversalAccessFromFileURLs = true;
   app_web_settings.DomStorageEnabled = true;
   app_web_settings.DatabaseEnabled = true;
   app_web_settings.SetRenderPriority(WebSettings.RenderPriority.High);
   app_view.SetLayerType(LayerType.Hardware, null);
   my_web_client = new MyWebViewClient(this);
   web_client = new WebChromeClient();
   app_view.SetWebViewClient(my_web_client);
   app_view.SetWebChromeClient(web_client);

  string app_url = "file:///android_asset/app_pages/home.html";
  app_view.LoadUrl(app_url);
  app_view.AddJavascriptInterface(new Foo(this), "foo");
}

标签: jqueryajaxxamarinxamarin.androidandroid-webview

解决方案


我更改了我的 ajax 请求并使用 jsonp 方法。它在发布模式下成功运行。

 $.ajax({
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        url: 'http://****.com',
        data: data,
        dataType: "jsonp",
        success: function(data, status) {
          alert('success')
        },
        error: function(xmlRequest) {
          alert('error')
        }
      });

推荐阅读