在framework7(最新版本)中,有一些示例页面,例如page-loader-component.html。该页面具有-
<p>Hello {{name}}</p>
底部有脚本
return {
data: function(){
return{
name: "Peter"
}
}
}
现在访问该页面时,它会显示-你好彼得
问题是我想从服务器的真实数据库中获取名称。所以我进行了更改-
app.request.post(
'http://domain-name/page.php',
{userid: 2},
function(response){
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
return {
data: function(){
return response //console log shows response is not defined
}
}
现在,当尝试访问该页面时,它会引发错误(在控制台中)- ReferenceError:未定义响应。在控制台中,我的请求查询正常,它显示- {name:“ Peter”}
我确实返回了响应,并尝试替换了函数的位置,并尝试了关于stackoverflow的其他建议。
我认为一个功能正在运行,而另一个功能尚未完成数据库查询。我不是专家(只是中等水平)。所以请有人提出建议。
我也曾尝试通过route.js访问该页面,例如request-and-load.html中给出的示例,但仍然引用错误。
答案 0 :(得分:0)
我认为您必须经过async route
才能加载页面上下文(参见F7 doc)
您将能够通过resolve
回调
也许一个例子可以帮助您:async data for page
答案 1 :(得分:0)
return response
在data:
部分中。请求不是,他们无法互相联系。
将数据收集放入数据功能内。您还希望将响应保存在请求功能之外。确保响应变量可访问。我还亲自将请求本身移动到一个单独的位置,以在该实例之外使用。
文件:custom.js
requests = {
GetName: function () {
app.request.post(
'http://domain-name/page.php',
{ userid: 2 },
function (response) {
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
},
GetNameDynamic: function (id) {
app.request.post(
'http://domain-name/page.php',
{ userid: id},
function (response) {
var response = JSON.parse(response);
console.log(response);
return response
}
);
}
}
然后在data:
部分中调用该函数并将其另存为变量。将其传递给数据返回。
data: function () {
// Must return an object
var result = requests.GetName();
return {
name: result.name,
}
},
还有其他方法/位置可以完成此操作。一个是另一个用户提到的异步路由。 在路由数组中,只需将path和componentUrl更改为正确的路径即可。
{
path: '/post-entity-group/:type/:group/:public/',
async: function (routeTo, routeFrom, resolve, reject) {
var result = requests.GetName();
resolve(
{
componentUrl: './pages/post-entity.html',
},
{
context: {
name: result.name,
}
}
)
}
},