我有一个json文件results.json,如下所示。我有一个html文件包含了一些脚本。这是为了检索数据数据。当我进入html页面时,它调用了一个脚本函数get_machFollow(que_script),这个函数用于接收json文件数据。该函数工作正常,并且警告输出正确,但是在此函数之后,将一些数据返回到我的HTML页面。
我的JSON文件
{"mach_fol_4": {"match_l":
["7","8","99"],"attempts":"0","feedback_true":"You are right!",
"feedback_false":"Sorry! wrong answer."}}这是我的脚本功能。此函数工作正常,但我无法从HTML页面中通知返回值。显示出未定义。
function get_machFollow(que_script)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
return return_var;
});
}这是我的html文件
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(document).ready(function(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
alert(mach_follow_js);//Wrong output
});
</head>
<body>
<p>Hello world</p>
</body>
</html>发布于 2013-12-06 04:32:36
有多种方法可以做到这一点。其中之一是将回调处理程序传递给您的方法,当您得到响应时将被调用。试试这个:
function get_machFollow(que_script, sCallback)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
sCallback.call(null /* context */, return_var);
});
}
$(document).ready(function(){
var mach_follow_js;
get_machFollow('mach_fol_4', function(output) {
alert(output);
match_follow_js = output;
});
});发布于 2013-12-06 04:23:28
您是否打算返回return_var;在get_machFollow作用域中,因为它现在在jquery函数范围内,不会将值返回到主页面。
发布于 2013-12-06 05:06:49
下面是AJAX获取的JSON数据。它在Alert中传递JSON数据对象。你想怎么用就怎么用。还可以使用for循环或$.each函数迭代数据。
$(document).ready(function(){
var mach_follow_js;
// mach_follow_js=get_machFollow('mach_fol_4');
//JSON Data Fetched by AJAX
$.ajax('results.json',{
type:'GET',
dataType: "json",
jsonCallback: 'successCallback',
async: true,
beforeSend: function () {
//if you want to show loader
},
complete: function () {
//hide loader after download data
},
success: function (resultJSON) {
mach_follow_js = resultJSON; // assigning to Global variable ProductResult
alert(mach_follow_js);
console.log(mach_follow_js);
},
error: function (request, error) {
alert('Network error has occurred please try again!');//error
}
})
});https://stackoverflow.com/questions/20415896
复制相似问题