2012-06-18 81 views
1

我想從查詢字符串中獲取我的數據,但使用它與Ajax。 我不能似乎得到的數據正確地傳遞,我想知道我的語法是錯誤的:

$(function() 
     { 
    $("#link").click(function(event) 
    { 
    event.preventDefault(); 
     $.get("request.php",{id:+link.attr('id')},function(response){ 

       $("#ajaxresponse div").fadeOut("fast", function() 
       { 
        $("#ajaxresponse div").remove(); 
        $("#ajaxresponse").append($(response).hide().fadeIn()); 
       }); 

      } 
     }); 
     return false; 
    }); 
}); 

HTML頁面代碼:

<div class="content"> 

<a href="request.php?id=1" id="link"> 


</div> 

我不是數據正確地構建以Ajax調用??

在此先感謝

我能得到正常的回報,而不是在阿賈克斯的方式,它仍然加載PHP頁面,而不是其附加的,這裏是東西方request.php:

$username = $_GET['id']; 


echo getTemplate($username); 

function getTemplate($username) 
    { 
return '<div class="box"> 
    <h1>ID is</h1> 
    <div class="meta">username: '.$username.'</div> 
</div>'; 

    } 

回答

0

添加任何其他功能外,此功能:

function getUrlVars(url){ 

    var vars = [], hash; 
    var hashes = url.slice(url.indexOf('?') + 1).split('&'); 
    for(var i = 0; i < hashes.length; i++){ 
     hash = hashes[i].split('='); 
     vars.push(hash[0]); 
     vars[hash[0]] = hash[1]; 
    } 
    return vars; 
} 

然後使用:的

getUrlVars($(this).attr("href"))["id"] 

代替

link.attr('id') 

演示http://jsfiddle.net/zY9s2/

+0

感謝您的幫助! – Jjames

+0

@Jjames我很好,我可以幫你 – mgraph

0
{id:+link.attr('id')} 

應該

{ id: link.attr('id') } 
1

可以使用效用函數這樣

function getParameterByName(name,url) { 

    var match = RegExp('[?&]' + name + '=([^&]*)') 
        .exec(url); 

    return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); 

} 

,然後在你的代碼中使用它使用它像

$("#link").click(function(event) 
    { 
    event.preventDefault(); 
    var id = getParameterByName('id',$(this).attr('href')); 
     $.get("request.php",{id:id},function(response){ 

演示:http://jsfiddle.net/joycse06/dPX2h/