javascript - 返回结果会更改 javascript JSON 字符串中的数据

标签 javascript json

我有以下代码:

function bestMove() {
  var url = "http://www.api.com"; // supposed to send {"location":4} in json format.
  $.getJSON(url, function(data) {
    console.log(data);
    return data;
  });
}

$(function() {

  console.log(bestMove())
  //driver code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

bestMove() 中的函数 console.log(data); 记录 {location:4} (这就是我想要的),但函数之外的记录未定义。但是,返回的是变量数据,为什么值会不同呢?

另外,当我使用 JSON.parse(data) 时,Chrome 返回此错误:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success (tictactoe:5)
    at u (jquery-3.3.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
    at k (jquery-3.3.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)

最佳答案

您应该能够对代码进行以下更新以实现您的目标:

function bestMove() {
  var url = "http://www.api.com"; // supposed to send {"location":4} in json format.

  // Return the result of $.getJSON 
  return $.getJSON(url, function(data) { 
    console.log(data);
    return data;
  });
}

$(function() {

  // Add a then handler after bestMove() is called. The function
  // handler will give you access to driver data returned from to
  // ajax response
  bestMove().then(function(driver) {

    //driver code here
    console.log(driver)
  })
});

关于javascript - 返回结果会更改 javascript JSON 字符串中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031874/

相关文章:

javascript - 带有空值的 ExtJS JSON 记录

javascript - 将变量操作数应用于运算符

javascript - WicketPDF 渲染表未正确对齐且页脚位于最后一页

javascript - 将数据存储在服务器上,无需数据库

javascript - react 路由器 : render is not a function

javascript - 为要使用的 jquery 函数添加多个参数的正确方法

javascript - 如果某些条目受到安全规则的限制,child_added 仍然有效吗?

在 swift 4 中使用 Alamofire 发出请求时来自服务器的 JSON 解析错误

python - 复杂的 Python JSON 对象到自定义字典的转换

javascript - 解析 json 并在弹出窗口中显示图像