开发者

Using jQuery's ajax get request with parameters, returning page content

I'm trying to use jQuery's get function to call my php script. The php script returns a variable containing the built template of the main content of my page minus my static header/footer.

I would like to use the returned content to replace the "old" page content without the page reloading. Can anyone point me in the right direction as to where I'm going wrong here? My code is as follows...

jQuery:

function getData(time, type) {
     $.ajax({
            type: "GET",
            url: "getData.php",
            data: "time=" + time + "&type=" + type,
            success: function(data){
               $('#pageContent').fadeOut("slow");
               $('#pageContent').html(data);
               $('#pageContent').fadeIn("slow");
     }
    });
    return false;
}

getData.php(paraphrased):

    ....

    $time = empty($_GET['time']) ? '' : $_GET['time'];
    $type = empty($_GET['type']) ? '' : $_GET['type'];
    echo getData($time, $type);

    function getData($time, $type)
    ......
        .....
            $tmpl = new Template();
            $tmpl->time= $time;
            $tmpl->type = $type;
            $builtpage = $tmpl->build('index.tmpl');
            return $builtpage;
        .....
    ......

jQuery function call:

<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Orange')">Orange</a>
<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Apple')">Apple</a>
<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Banana')">Banana</a>

When I click any link, the开发者_StackOverflow社区 ajax seems to run fine, and the page does refuse to reload, but the content still remains unchanged... Anyone happen to know what's up?


First in the success function, check to make sure that you are receiving what you are looking for:

success: function(data){
  alert(data);
}

Also in the php file, try putting this on top of the script:

header("Content-Type: text/html");

And try modifying your code like:

success: function(data){
  $('#pageContent').html(''); // remove what was before
  $('#pageContent').fadeOut("slow");
  $('#pageContent').html(data);
  $('#pageContent').fadeIn("slow");
}


The Ajax will not run fine:

<a href="#" onclick="getData("<?php print $tmpl->time; ?>", "Orange")">Orange</a>
                             ^
                             End of attribute value here

Use a validator and nest your quotes correctly (by switching between " and ' or using entities).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜