未能为不同页面中使用的全局变量定义成功函数



原例

失败的例子

请看看这个:

$.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 () {}
});

我有一个ajax脚本,其中的成功回调函数是非常特定于页面的,就像在某些页面上一样,我宁愿使用它来构建标记:

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

我可以把这个成功回调函数作为一个全局变量,并在特定的页面上包含它的修改版本,像这样:

在主JS文件中:

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

页面文件:

<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>

试试这个

$.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+'')
    });
};

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

最新更新