2013-10-25 3 views
0

나는 index.html에 있으며, 나는 ajax query.php을 얻었습니다. 이제 block.htmlcontent에로드하기 전에 색상/크기 정보없이 텍스트가 나타나지 않게하려면 어떻게해야합니까?로드 된 내용을 표시하기 전에 채우는 방법?

index.html을

<div id="content"><button id="button1" type="button">click</button></div> 

block.html

You selected the color: <div id="color"></div>! 
You chose a size of: <div id="size"></div>! 

query.php

$result = array('color' => 'blue', 'size' => '12'); 
echo json_encode($result); 
+0

왜 자신의 파일 block.html입니까? –

+0

여러 단계가 있습니다. 하나의 단추를 클릭하면 block.html이 내용으로로드되고 다른 단추를 클릭하면 block2.html이로드됩니다. – Roger

답변

1

당신은 일부 데이터와 y를 몇 가지 HTML이 있으며 합리적인 방법으로 함께 병합해야합니다. 기본적으로는 client-side templating입니다.

  1. $.get 당신이 필요로하고 jQuery를 객체 processBlock()
  2. $.get 당신이 # 2 renderBlock($el, data)
  3. 의 결과 getDataFor($el)
  4. 업데이트 # 1을 필요로하는 데이터로 변환하려면 HTML :

    여기에 하나의 기본적인 접근 방식

  5. 업데이트 된 HTML을 DOM에 삽입하십시오. addToContent($el)
,210

코드 : 비 JQuery와 땅에서

$.get("block.html", processBlock); 

// create a documentFragment to fill in later 
function processBlock(html) { 
    var $block = $(html); 
    getDataFor($block); 
} 

// get any needed data by querying for JSON 
function getDataFor($el) { 
    $.getJSON("query.php", function(data) { 
     renderBlock($el, data); 
    }); 
} 

// take the data and the element and 
function renderBlock($el, data) { 
    $el.find("#color").text(data.color); 
    $el.find("#size").text(data.size); 
    addToContent($el); 
} 

function addToContent($el) { 
    $el.appendTo($("#content")); 
} 

당신이 DOM을 사용하면 페이지에 삽입하기 전에 조작 조금을 만들 수있는 DocumentFragment가라는 뭔가를 만드는 것입니다.

간단한 바이올린 버전 : http://jsfiddle.net/9kLzP/

관련 문제