如何从脚本页面返回json数据

How to return back json data from script page?

本文关键字:返回 json 数据 脚本      更新时间:2024-04-21

我有一个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函数。因此,您需要应用回调来执行此操作。