將ajax請求到的數(shù)據(jù)用回調(diào)函數(shù)返回

Paste_Image.png

由于ajax的異步問題,全局變量bookData輸出的時候不一定已經(jīng)執(zhí)行完成ajax,所以存在獲取不到請求數(shù)據(jù)的情況酪耕。這里把將變量作為回調(diào)輸出,可以保證獲取的是返回的數(shù)據(jù)轨淌。
index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="./css/index.css">
  
</head>
<body>
    <div id="todoList"></div>
    <ul id="bookTypeList" class="bookType"></ul>
    <div class="clear"></div>
    <table id="bookList" class="bookList">
        <thead>
            <tr>
                <th>書名</th>
                <th>作者</th>
                <th>編號</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script type="text/template" id="type-list-template">
        {{#.}}
            <li>{{type}}</li>
        {{/.}}
    </script>

    <script type="text/template" id="book-list-template">
        {{#.}}
            <tr>
                <td>{{name}}</td>
                <td>{{author}}</td>
                <td>{{bookNo}}</td>
            </tr>
        {{/.}}
    </script>

    <script type="text/javascript" src="./js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="./js/mustache.min.js"></script>
    <script src="./js/main.js"></script>
    <script type="text/javascript">
        $("#bookTypeList li").eq(0).addClass("active");

    // todoList
    $.ajax({
        url:"/v1/foobizzle.json",
        method:"get",
        success:function(data){  
            var resultHtml = "<ul>";
            for(var i=0; i<data.length; i++){
                resultHtml += "<li>" +data[i].title+" - " +(data[i].done?"完成":"未完成") + "</li>";
            }
            resultHtml += "</ul>";
            $("#todoList").html(resultHtml);
        }
    });

    // tab switch
//使用mustache模板迂烁,先創(chuàng)建模板html,然后在js中獲取模板tpl,[Mustache.parse(tpl)]
    var bookData;
    function getBook(callback){
        $.ajax({
            url:"/v1/book.json",
            method:'get',
            success:function(data){
                bookData = data;

                var tTypeList = $("#type-list-template").html();
                Mustache.parse(tTypeList);
                $("#bookTypeList").append(Mustache.render(tTypeList,data));

                var tBookList = $("#book-list-template").html();
                Mustache.parse(tBookList);
                $("#bookList tbody").html(Mustache.render(tBookList,data[0]['books']));
                $("#bookTypeList li").click(function(){
                    var idx = $(this).index();
                    $("#bookList tbody").html(Mustache.render(tBookList,data[idx]['books']));
                    $(this).addClass("active").siblings().removeClass("active");
                });
                callback(bookData);
            }
        });
    }
    
    getBook(function(data){
        console.dir(data);
    });

    </script>
</body>
</html>

book.json:

[{
    "type":"名著",
    "books":[{
        "name":"西游記",
        "author":"黃承恩",
        "price":123.00,
        "bookNo":"M001"
    },{
        "name":"紅樓夢",
        "author":"曹雪芹",
        "price":110.00,
        "bookNo":"M002"
    }]
},{
    "type":"動漫",
    "books":[{
        "name":"黑貓警長",
        "author":"毛毛",
        "price":23.00,
        "bookNo":"D001"
    },{
        "name":"多啦A夢",
        "author":"啊啊",
        "price":23.00,
        "bookNo":"D002"
    }]
}]

引入文件(mustache.js):

(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.2.1";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末递鹉,一起剝皮案震驚了整個濱河市盟步,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌躏结,老刑警劉巖却盘,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異媳拴,居然都是意外死亡黄橘,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進(jìn)店門屈溉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來塞关,“玉大人,你說我怎么就攤上這事子巾》” “怎么了小压?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長椰于。 經(jīng)常有香客問我怠益,道長,這世上最難降的妖魔是什么廉羔? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任溉痢,我火速辦了婚禮,結(jié)果婚禮上憋他,老公的妹妹穿的比我還像新娘孩饼。我一直安慰自己,他們只是感情好竹挡,可當(dāng)我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布镀娶。 她就那樣靜靜地躺著,像睡著了一般揪罕。 火紅的嫁衣襯著肌膚如雪梯码。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天好啰,我揣著相機(jī)與錄音轩娶,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的盯拱。 我是一名探鬼主播腌巾,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤贤重,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后清焕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體并蝗,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年秸妥,在試婚紗的時候發(fā)現(xiàn)自己被綠了借卧。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡筛峭,死狀恐怖铐刘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情影晓,我是刑警寧澤镰吵,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布檩禾,位于F島的核電站,受9級特大地震影響疤祭,放射性物質(zhì)發(fā)生泄漏盼产。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一勺馆、第九天 我趴在偏房一處隱蔽的房頂上張望戏售。 院中可真熱鬧,春花似錦草穆、人聲如沸灌灾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽锋喜。三九已至,卻和暖如春豌鸡,著一層夾襖步出監(jiān)牢的瞬間嘿般,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工涯冠, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留炉奴,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓蛇更,卻偏偏與公主長得像瞻赶,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子械荷,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理共耍,服務(wù)發(fā)現(xiàn)虑灰,斷路器吨瞎,智...
    卡卡羅2017閱讀 134,712評論 18 139
  • 3月15日 1. 下列JavaScript代碼執(zhí)行后,依次alert的結(jié)果是穆咐? 1 3 undefined -1 ...
    福爾摩雞閱讀 1,943評論 0 4
  • Ajax的基本概念及使用 同步&異步 同步:必須等待前面的任務(wù)完成颤诀,才能繼續(xù)后面的任務(wù); 異步:不受當(dāng)前主要任務(wù)的...
    magic_pill閱讀 1,958評論 0 5
  • 我在這 在這里 還在原點徘徊对湃、躊躇 我們有不同的人生不同的故事 就像海天相接 縱然彼此靠近崖叫,但仍有一道深深的印痕 ...
    舊時相識閱讀 187評論 0 1
  • 有段時間沒寫點東西了,一則是自己慵懶拍柒,另一則是沒讀到足夠吸引我的東西心傀。《大江東去》拆讯,從我觸到的一刻就吸引到了我...
    FFxin閱讀 241評論 3 2