如何从脚本页面返回json数据
How to return back json data from script page?
我有一个json文件results.json如下所示。我有一个html文件包含一些脚本。这是用于检索数据数据。当我进入调用脚本函数get_machFollow(que_script)
的html页面时,该函数用于接收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>
您是否打算返回return_var;在get_machFollow范围内,因为现在它在jquery函数范围内,不会将值返回到主页
下面是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
}
})
});
有多种方法可以做到这一点。其中之一是将回调处理程序传递给您的方法,该方法将在您获得响应时被调用。试试这个:
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回调函数$.getJSON()
实际上是一个ajax函数。因此,您需要应用回调来执行此操作。
相关文章:
- Jquery:对返回JSON数据的php脚本的Ajax调用
- 返回JSON中的下标
- jQuery Map 从多个源返回 JSON 对象
- 如何在 Node.js 中返回 JSON 后停止代码流
- AngularJS:表单提交没有返回JSON中的值
- 使用ajax发送数据,返回json
- 从我的解析函数返回json
- 如何从脚本页面返回json数据
- 有些人有任何关于如何使用Modified Java Script Value处理返回Json(url)的示例
- 如何在html页面中从ajax返回json数据
- Ajax调用在本地返回json,但在服务器上运行时返回xml
- ajax调用返回JSON ParseError即使认为JSON看起来是正确的
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何通过C#返回JSON并用JavaScript进行解析
- 使用 AJAX 返回 json 数组
- 从 AJAX 命令返回 JSON 格式的响应
- 如何通过node中的请求返回JSON.js(从javascript)
- Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
- 如何在支柱 2 中返回 JSON 数组
- Rhino:从 Java 中返回 JSON