Javascript 如何从脚本页面返回json数据?
我有一个json文件results.json,如下所示。我有一个html文件包含一些脚本。这是用于检索数据的。当我进入调用脚本函数的html页面时,Javascript 如何从脚本页面返回json数据?,javascript,jquery,html,json,Javascript,Jquery,Html,Json,我有一个json文件results.json,如下所示。我有一个html文件包含一些脚本。这是用于检索数据的。当我进入调用脚本函数的html页面时,get\u machFollow(que\u script)此函数用于接收json文件数据。该函数工作正常,提示正确输出,但在此函数之后,将一些数据返回到我的HTML页面 我的JSON文件 {"mach_fol_4": {"match_l": ["7","8","99"],"attempts":"0","feedback_true":"
get\u machFollow(que\u 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>
$(文档).ready(函数(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
警报(马赫跟随);//输出错误
});
你好,世界
您是否打算退货;要在get_machFollow范围内,因为现在它在jquery函数范围内,不会将值返回到主页有多种方法可以做到这一点。其中之一是将回调处理程序传递给您的方法,当您得到响应时将调用该方法。试试这个:
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;
});
});
下面是AJAX获取的JSON数据。它在警报中传递JSON数据对象。 你可以随心所欲地使用它。还可以使用for循环或$。每个函数迭代数据
$(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
}
})
});
使用ajax回调函数
$。getJSON()
实际上是一个ajax函数。因此,您需要应用回调来执行此操作。那么如何获取此值?我需要的是一个解决方案而不是建议。我没有用jquery尝试过这一点,但请检查$.getJSON方法返回的内容。如果它不是空的,您可能可以分配return\u var=$.getJSON。。。,但是将返回值保留在getJSON中,并向外部函数$添加一个新的返回值。getJSON返回一些无用的对象,以显示函数已准备就绪。$。getJSON
是一个异步调用,因此当您调用get\u matchFollow
并尝试在下一行中警告响应时,来自ajax的响应还没有到来。这就是为什么它没有定义给我一个从这个$GetJSONObly的副本中获取值的想法