使用回调打印json数据

时间:2018-01-22 16:31:30

标签: javascript json callback

尝试从php文件中获取我的json数据并显示。

到目前为止,我能够使用ajax请求数据并将数据记录到控制台。 (至少有一件事似乎有效)。

然后我尝试使用回调,所以我的脚本会在执行显示功能之前等待数据。我一步一步地遵循了这个教程,但我必须做错事,因为在检查器中它会抛出一个错误,我的jsonData没有被定义。

然后我尝试显示数据,但如果没有回调正常工作,它将无效。

我将尝试解释我的所作所为:

1。 我在运行脚本之前等待文档加载

$(document).ready(scriptWrapper);

2。 我用一个函数包装整个事件

function scriptWrapper(){
  displayJson();
}

3。 我用我的回调参数

启动该函数
function requestJson(_callback){ 

4。 使用ajax

从我的php文件中请求我的数据
$.ajax({
    url: "/test/senate.php",
    success: result,
});

5。 将数据结果发送到console.log

function result(jsonData){
    console.log (jsonData);
}

6。 这标志着回调的结束

_callback();

7。 启动displayJson函数

function displayJson(){

8。 使用requestJson()函数执行showData()作为参数,我认为showData将在执行前等待回调。

requestJson(showData());

9。 这个函数将在我的输出div中显示json数据。

function showData(){
    $(".output").append(jsonData);
}

任何见解都将受到赞赏!

我在这里有一个实时版congress.digitango.com/test/results.php

完整的代码是:

<div class="output"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function scriptWrapper(){
  displayJson();
}

function requestJson(_callback){ 
  $.ajax({
    url: "/test/senate.php",
    success: result,
  });

  function result(jsonData){
    console.log (jsonData);
  }
  _callback();
}

function displayJson(){
  requestJson(showData());
  function showData(){
    $(".output").append(jsonData);
  }
}
$(document).ready(scriptWrapper);  
</script>

3 个答案:

答案 0 :(得分:2)

您的整个代码都是样板文件。除了调用其他函数和彼此以及回调之外什么也不做的空函数......这让人感到困惑和毫无意义。你过度工程了。不要那样做。

您可以将所写的所有内容压缩为3行。

<div class="output"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
  $.getJSON("/test/senate.php").done(function (data) {
    $(".output").append(data);
  });
</script>

答案 1 :(得分:1)

您指定为success 的函数是回调函数。它将根据请求的结果调用:

function requestJson () { 
  $.ajax({
    url: "/test/senate.php",
    success: result // call the 'result' function when you're done
  });

  function result (jsonData) {
    // do something with the data
  }
}

然后你可以这样做:

function requestJson (callback) { // we accept the callback function as the parameter
  $.ajax({
    url: "/test/senate.php",
    success: callback, // call the callback function when you're done
  });
}

function displayJson () {
  requestJson(showData); // use 'showData' as the callback function

  function showData (jsonData) {
    $(".output").append(jsonData);
  } 
}

答案 2 :(得分:1)

以下是我将如何修复和简化代码

<script type="text/javascript">

function scriptWrapper(){
  requestJson();
}

function requestJson(){ 

  $.ajax({
    url: "/test/senate.php",
    success: displayJson,
  });

}

function displayJson(jsonData){

  $(".output").append(jsonData);

}

$(document).ready(scriptWrapper);  

</script>

我目前无法运行代码,但您可能还需要更改$(“。output”)。append(jsonData); to $(“。output”)。first()。append(jsonData);

JQuery's $.ajax documentation has some helpful example of how to use callbacks