javascript - JSON AJAX - 返回空对象

标签 javascript jquery ajax json

<分区>

我在函数中使用 AJAX 调用来从服务器检索一些数据,方法如下:

getPolicies: function() {
  $.ajax({
    async: false, // wait for response
    type: "GET",
    url: "http://localhost:8080/getPolicies",
    contentType: "application/json",
    dataType: "json",
    success: function(jsonList) {
      for(var i in jsonList) {
        console.dir(jsonList[i].policyName);
      }
      return jsonList;
    },
    failure: function(err) {console.log("Error");}
  });
}

我正确地得到了 JSON 数组:

[ 
  { 
    "policyName": "policy1"
  },
  { 
    "policyName": "policy2"
  },
  { 
    "policyName": "policy3"
  }
]

此 JSON 数组由函数返回。 但是当我调用函数 getPolicies() 时,我只得到一个空的 JSON 对象 {}。具体来说,如果我尝试

var policies = getPolicies();
console.log(policies[1].policyName);

我明白了:

Uncaught TypeError: Cannot read property 'policyName' of undefined

那么,即使我正确获取了 JSON 数组,该函数怎么可能返回一个空对象?! 谢谢...

最佳答案

即使 AJAX 请求是同步的 *),return 语句仍然只从成功处理程序返回。尝试这样的事情:

getPolicies: function() {
  // Declare variable here
  var resultList = null;

  $.ajax({
    async: false, // wait for response
    type: "GET",
    url: "http://localhost:8080/getPolicies",
    contentType: "application/json",
    dataType: "json",
    success: function(jsonList) {
      for(var i in jsonList) {
        console.dir(jsonList[i].policyName);
      }
      // Set the variable in the scope of getPolicies.
      resultList = jsonList;
    },
    failure: function(err) {console.log("Error");}
  });

  // This one actually returns getPolicies
  return resultList;
}

但一般来说,使 AJAX 调用同步被认为是不好的做法。相反,您可以更好地从成功处理程序中调用必要的功能。这也可以是另一个功能。例如,您可以声明

function processPolicies(policies)
{
  console.log(policies[1].policyName);
}

你的调用处理程序可以是这样的(:

$.ajax({
  async: true, // just let it run,
  type: "GET",
  url: "http://localhost:8080/getPolicies",
  contentType: "application/json",
  dataType: "json",
  success: function(jsonList) {
      processPolicies(jsonList);
  },
  ...

*) 第一个 A 甚至代表异步。但另一方面,X 代表 XML,因此您在这里所做的实际上应该称为 JaJ 而不是 AJAX。 ;)

关于javascript - JSON AJAX - 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605390/

相关文章:

javascript - 拖动按钮时将光标更改为十字线

javascript - Jquery Bootstrap Modal...如何从另一个模式对话框中打开不同的模式对话框

javascript - 使用ajax动态添加时Html视频显示白屏

javascript - 多行工具提示无法以编程方式工作

javascript - vite.config.js rollupOptions 在构建过程中导致 "Unexpected token"错误

javascript - 如何从 URL 获取 JSON 并将其值设置为文本字段?

php - Ajax请求并使用php pdo复制一些行但更改一些值

javascript - jQuery Datatable 让每个单元格成为一个链接

jQuery 语法错误 : #/

javascript - 使用ajax将数据附加到现有数据表的正确方法