Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 回调函数在以下代码中不工作?_Javascript_Html - Fatal编程技术网

Javascript 回调函数在以下代码中不工作?

Javascript 回调函数在以下代码中不工作?,javascript,html,Javascript,Html,下面的代码应该显示一个随机引用。但它什么也没回来。只是显示html页面布局。以下javascript回调函数不起作用的原因: $(文档).ready(函数(){ 函数cb(){ var addr=”http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts\u per\u page]=1”; $.getJSON(地址,函数(rslt){ 返回rslt; }); }; 功能qte(rslt){ $(“#qti

下面的代码应该显示一个随机引用。但它什么也没回来。只是显示html页面布局。以下javascript回调函数不起作用的原因:

$(文档).ready(函数(){
函数cb(){
var addr=”http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts\u per\u page]=1”;
$.getJSON(地址,函数(rslt){
返回rslt;
});
};
功能qte(rslt){
$(“#qti”).html(rslt[0].content);
$(“#athr”).html(rslt[0].title);
};
qte(cb);
$(“#nqt”)。在(“单击”,函数(){
qte(cb);
});
$(“tit”)。在(“单击”,函数()上{
窗口打开(“https://twitter.com/intent/tweet?text=“+编码元件(qwe));
});
});

随机报价生成器
- 
新报价
您可以这样做。一旦异步调用的响应可用,则使用触发
qte
函数

$(document).ready(function() {
  function cb() {
    // changed http to https to avoid blockrd content
    var addr = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
   // returning the 'promise' from this function
   return $.getJSON(addr, function(rslt) {
    return rslt;
    });
  };

  // when cb function has finished execution using its result to populate the fields
  $.when(cb()).done(function(rslt){

   $("#qti").html(rslt[0].content);
    $("#athr").html(rslt[0].title);
  });
  // rst of code
});

getJSON回调是异步调用的,因此回调根本没有执行任何操作。您知道cb函数没有返回任何内容吗?您的浏览器具有内置调试器。这对于深入了解像这样的问题非常有帮助。我建议你花点时间学习使用它。这里可能有重复的使用承诺。Tnx。但它不起作用。当我使用alert时,它表示未定义。这意味着它从JSON调用中什么也得不到。但当我在浏览器窗口中访问那个url时,它给了我一个数组,这意味着url工作正常。