我有一个使用jQuery的项目,并且我有很多返回json的函数,我试图用一些测试数据填充数据变量,但是当我遍历数据时却一无所获。
我已经检查过,以确保我的ajax调用正在返回json数据,而且确实如此,而且我对为什么什么都不返回感到困惑
<div id="app">
<template v-for="person in persons">
<div>
{{ person.FirstName }}
</div>
</template>
</div>
<script>
new Vue({
el: '#app',
created: function () {
this.GetUserDetails();
},
data: {
persons: []
},
methods: {
GetUserDetails() {
this.persons = CommonFunctions.GetJSON("Person");
}
}
});
</script>
以下是Person json,
[{
"id": 1,
"FirstName": "Auroora",
"LastName": "Kosel",
"gender": "Female"
},
{
"id": 2,
"FirstName": "Nevins",
"LastName": "Rulf",
"gender": "Male"
},
{
"id": 3,
"FirstName": "Silvana",
"LastName": "Cragoe",
"gender": "Female"
}]
**编辑** 这是GetJSON函数
var CommonFunctions = {
GetJSON: (whichOne) => {
$.ajax({
type: "GET",
url: "../Scripts/" + whichOne + "JSON.json",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
return data;
}
});
}
}
答案 0 :(得分:1)
您的GetJSON()
函数不返回任何内容。
var CommonFunctions = {
GetJSON(whichOne) {
return $.getJSON("../Scripts/" + whichOne + "JSON.json");
// ^^^^^^
}
}
Now it returns the request/promise (and uses jQuery's shorthand method for retrieving json).
您将在组件中编写
async GetUserDetails() {
this.persons = await CommonFunctions.GetJSON("Person");
}
或者如果您不喜欢异步/等待:
CommonFunctions.GetJSON("Person").then(data => {
this.persons = data;
});
答案 1 :(得分:1)
据我了解,ajax函数是异步的,因此不会直接返回
有一个简单的解决方法:
import locale
locale.setlocale(locale.LC_ALL, 'C')
import tesserocr
和辅助功能:
methods: {
GetUserDetails() {
this.persons = CommonFunctions.GetJSON("Person", this);
}
}