【问题标题】:AngularJS $http and jQuery AJAX not firing on Mobile Browsers onlyAngularJS $http 和 jQuery AJAX 仅在移动浏览器上不触发
【发布时间】:2015-05-21 14:54:27
【问题描述】:

我有一个非常简单的角度测试应用程序,它调用$http.get('http://localhost:3001/pets') 并使用 ngRepeat 作为 s 将它们写入 index.html

URL 返回 Array,其中包含 3 个对象,如下所示:

[
    {
      "id": 1,
      "name": "cat",
      "location": "bedroom"
    },
....
]

然后使用 .success() 将其分配给 $scope.pets(实际代码如下)。

这适用于所有桌面浏览器。

但是,当我使用 Chrome 或 Firefox(以及诺基亚上的 IE)在我的 Android 上加载页面时,什么也不做。 没有效果 - NodeJS/Express 甚至似乎都没有收到请求。

我尝试将 $http.get 替换为 $.ajax (... $scope.$apply...) - 代码如下。

我尝试使用服务、$defered 和 $q,如下所述:http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

当我将 Chrome Mobile/Firefox 直接指向 API (http://localhost:3001/pets) 数据加载到浏览器没有问题。 我尝试对这些值进行硬编码,如下所示:

$scope.pets = [{"id": 1000, "name": "GOAT", "location": "EVERYWHERE"}];

... 并执行 ngClick 以调用 $http.get 并覆盖这些值。

同样,在桌面上运行良好 - 在移动设备上没有任何作用。

我确定我已经添加了 CORS 标头:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Headers: X-Requested-With,content-type
Access-Control-Allow-Credentials: true

为什么?为什么这在手机浏览器上不起作用? 我用谷歌搜索了 2 天....

$scope.getPets = function () {
      $http.get('http://localhost:3001/pets')
    .success(function(response){
        //$scope.httpPets = response;
        console.log('Hello, this is dog with your GET request.')
        console.log(response);
    })
    .error(function(err){
      console.log("ERROR", err)
    })
    .then(function(response){
      console.log('Here then', response.data);
      $scope.httpPets = response.data;
    })
};

或者这个:

$scope.getPets = function(){
 $.ajax('http://localhost:3001/pets').success(function(data) {
        $scope.$apply(function(){ $scope.pets = data;});
        console.log(data);
    });
};

提前感谢您的任何建议。

【问题讨论】:

    标签: jquery ajax angularjs mobile


    【解决方案1】:

    检查您的网址。它说 localhost,因此除非您的服务器驻留在移动设备中,否则它将无法工作(localhost 表示服务器存在于同一台机器上)。

    您需要提供正确的网址。

    这意味着,如果您使用移动浏览器,您可能会在地址栏中提供 url,例如。

    http://192.168.1.2/
    

    所以http调用应该是:

    $http.get('http://192.168.1.2:3001/pets')
    

    您只需要对这个 url 进行 http 调用。

    其他方式(广泛用于网站)是使用相对 URL,此方法将调用您所在的域并适用于所有站点。 例如,

    $http.get('/pets')
    

    将等于

    $http.get('http://192.168.1.2:3001/pets')
    

    检查这些..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 2020-11-06
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多