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

标签 javascript jquery html json

我有一个 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 函数范围内并且不会向主页返回值

关于javascript - 如何从脚本页面返回json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20415896/

相关文章:

javascript - 从 Soundcloud 嵌入的动态音频 &lt;iframe&gt;

javascript - 禁止禁用 Javascript 的用户浏览 Web 应用程序

jquery - 在 DOM 之后加载 jQuery,如何在加载 jQuery 之前使 $.ready() 可用于我的页面?

javascript - 获取数据表单元格的元素

javascript - 使用 jquery 验证克隆的复选框和单选按钮

javascript - 直接将服务注入(inject) AngularJS 指令 Controller

php - JQuery .get() 仅在 url 中传递前两个数据参数

jquery - 需要帮助使用 ColdFusion 和 jsTree 复制目录结构

javascript - 将选项数组传递给 jquery 插件

html - 我如何将此 <ul> 对齐到右边?