2011-11-08 27 views
0

私は現在、テキストリンクからAJAX呼び出しを行うことができるjQueryの一部を開発中です。これは問題ありませんが、テキストリンクには、AJAXリクエストを正しく実行するために、AJAXリクエストに送る必要のあるパラメータがあります。テキストリンクからURLパラメータを取得し、AJAXコールへの投稿

マイテキストリンクは、このようなものになります。ここでは

<a href="?affiliate=one&voteType=two">Click here</a> 

を私のjQueryのです:

function getUrlParam(name) 
{ 
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); 
    var regexS = "[\\?&]"+name+"=([^&#]*)"; 
    var regex = new RegExp(regexS); 
    var results = regex.exec(window.location.href); 
    if(results == null) 
    return ""; 
    else 
    return results[1]; 
} 


/* Let's create a function that will allow us to vote on the hosts */ 

function hostVote() { 

/* These variables are used to determine the button clicked */ 

    var affiliate = getUrlParam('affiliate'); 
    var voteType = getUrlParam('voteType'); 

    $.ajax({ 
     cache: false, 
     type: "POST", 
     url: "/php/hostvote.php", 
     data: "affilate=" + affiliate + "&voteType=" + voteType +"", 
     success: voteSubmitted 
    }); 

    function voteSubmitted() { 
     alert('Thanks for voting'); 
     $(this).addClass('yes'); 
    } 
    return false; 
}; 

$("a.vote").click(hostVote); 

このコードのトラブルが、私は、任意のパラメータを置くためにリンクを提出することはできませんです関数が実行される前にurlが返され、空のアフィリエイトとvoteTypeの値が返されます。

誰でも手助けできますか?代わりの

+0

テキストリンクから直接パラメータを抽出しないのはなぜですか? – Rodolphe

答えて

2

リンクのdata-*属性に必要なデータを格納する方がよい場合があります。これにより、対応するデータをより簡単に取得することができます。どのように動作するかの簡単な例があります。

<a href="#" data-affiliate="one" data-voteType="two">Click here</a> 

$("a.vote").click(function(e){ 
    var affiliate = $(this).data('affiliate'); 
    var voteType = $(this).data('voteType'); 
    // do your ajax call here 
    e.preventDefault(); 
}); 
0

-

var results = regex.exec($("a.vote").attr('href')); 

をし、あなたのリンクから直接変数を解析 -

var results = regex.exec(window.location.href); 

あなたは何ができますか?

関連する問題