我有以下代码:
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/