【问题标题】:JQuery $.post() responsejQuery $.post() 响应
【发布时间】:2017-01-15 10:41:29
【问题描述】:

您好,我对 $.post 调用的响应有疑问。

我会在表格中插入带有角度的数据。日期是 php 调用的响应。我用以下方式调用 php:

function AppCtrl($scope){
   $scope.seeTable = function(){
     $.post("/testJson.php", function(json){
       //setResponse(json); 
         $scope.contacts = json;
     });
   $scope.seeThisTable = !$scope.seeThisTable;
};
//Not working
function setResponse(json){
  $scope.contacts = json;
}

然后我在表格中插入:

 <tbody>
  <tr ng-repeat="contact in contacts">
   <td> {{contact.name}} </td>
   <td> {{contact.phone}} </td>
  </tr>
 </tbody>

我的php是:

<?php
$array = array(
            0 => array('name' => 'Peter',
                       'phone' => '555-5552'),
            1 => array('name' => 'Jhon',
                       'phone' => '555-1235'),
            2 => array('name' => 'Ron',
                       'phone' => '555-5122'),
            3 => array('name' => 'Harry',
                       'phone' => '555-5514')
         );

echo json_encode($array);
?>

但是 $scope.contacts 是空的。问题是提取 $.post() 的响应,但是当我尝试将 json 导出到函数 $.post() 时,它总是空的。我尝试调用另一个函数并在内部传递 json 但不起作用,在函数 setResponse 内部,json 正确但不设置 $scope.contacts,函数结束后 $scope.contacts 为空。

有什么方法可以提取响应?

谢谢!

【问题讨论】:

  • 你能为此创建 plunkr 吗?
  • json变量有数据吗?
  • 你可以尝试post方法的成功函数,只有在数据来自post之后才会调用它,然后你可以分配$scope.contacts=结果

标签: javascript jquery json


【解决方案1】:

像这样使用有角度的$http 服务..

function AppCtrl($scope,$http){
   $scope.seeTable = function(){
    $http({
            method:'GET',
            url:'/testJson.php'
        }).then(function  success(data,status,xhr){
            $scope.contacts = data.data;
            //console.log(data);
        },
        function error(data,status,xhr){
            alert(data.status);
        }
        }); 
}

AND HTML 部分

<tbody>
  <tr ng-repeat="contact in contacts">
   <td> {{contact['name']}} </td>
   <td> {{contact['phone']}} </td>
  </tr>
 </tbody>

【讨论】:

    【解决方案2】:

    问题是你在调用 $.post 时离开了 Angular 的作用域。那是 JQuery。

    解决方案:

    1) 使用 Angular 提供的 $http 服务

    2) 您可以在 post 响应方法中调用它。

    $timeout(function () {
       $scope.contacts = json
    });
    

    或者你可以调用 $scope.$apply

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2021-09-09
      • 2013-05-03
      • 1970-01-01
      • 2012-11-08
      • 2013-04-08
      • 1970-01-01
      相关资源
      最近更新 更多