简体   繁体   English

无法将成功函数定义为用于不同页面的全局变量

[英]Fail to define success function a global variable for use in different pages

Fiddle Original Example 小提琴原始示例

Failed Example 失败的例子

Please take a look at this: 请看一下这个:

$.ajax({
    url: "url",
    success: function (data) {

        $(data.query.results.json.json).each(function (index, item) {        
            var title = item.title;
            var ingredient = item.Ingredient; 
            $('.'+title).html(''+ingredient+'')

        });
    },
    error: function () {}
});

I have an ajax script in which the success callback function is very page-specific, like on certain pages, I'd rather use this to build the markup: 我有一个ajax脚本,其中成功回调函数是非常特定于页面的,就像在某些页面上一样,我宁愿使用它来构建标记:

   $(data.query.results.json.json).each(function (index, item) {        
      var title = item.title;
      var ingredient = item.Ingredient; 
      $('.'+ingredient).html(''+ingredient+'<p>+'title'+')
  });

Can I make this success callback function a global variable and have its modified versions include on specific pages, something like this: 我可以将此成功回调函数设为全局变量,并在特定页面上包含其修改后的版本,如下所示:

In the main JS file: 在主JS文件中:

var page_markup;
    $.ajax({
        url: "url",
        success: function (data) {
          page_markup();
        },
        error: function () {}
    });

In the page file: 在页面文件中:

<html>
<head>
<title>Title</title>  
<script type='text/javascript' src='jquery.min.js'></script>
<script type='text/javascript' src='mainjsfile.js'></script>
<script>
      page_markup = function(){
         $(data.query.results.json.json).each(function (index, item) {        
          var title = item.title;
          var ingredient = item.Ingredient; 
          $('.'+ingredient).html(''+ingredient+'<p>+'title'+')
         });
       }
</script>
<body>
text......
</body>
</html>

Try this 尝试这个

$.ajax({
    url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fgoo.gl%2F5Lpwxz%22&format=json&diagnostics=true&callback=",
    success: function (data) {
        mysuccess(data);
    },
    error: function () {}
});

var mysuccess =  function (data) {
    $(data.query.results.json.json).each(function (index, item) {        
        var title = item.title;
        var ingredient = item.Ingredient; 
        $('.'+title).html(''+ingredient+'')
    });
};

fiddle link: http://jsfiddle.net/9k3nT/ 小提琴链接: http//jsfiddle.net/9k3nT/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM