2015-07-13 108 views
0

我有一個AJAX函數,而且我對AJAX不好。我想將一個值從PHP傳遞給AJAX。我設法通過使用要做到這一點:使用href而不是輸入

<input type="text" id="price" onclick='ajaxFunction()' value="<?php echo $id; ?>" /> 

然後在我的AJAX:

document.getElementById('price').value; 

但我想,使其通過使用HTML A HREF工作。

任何人都可以幫助我做到這一點嗎?

提前致謝!

+1

做了哪些工作?如果你只是想要一個錨點,爲什麼不創建一個錨點。 – adeneo

+0

如何從A href中獲得價值,就是這個問題。 – Tibor

+0

@Tibor通過href ?!替換值 –

回答

5

anchor<a>標籤沒有value,而是它有innerHTML。用這樣的方式:

<a id="price" href="#something">50.00</a> 
document.getElementById('price').innerHTML; // 50.00 
document.getElementById('price').getAttribute("href"); // #something 

要設置這些值,你可以使用同樣的東西:

document.getElementById('price').innerHTML = responseText; 
document.getElementById('price').setAttribute("href", responseText); 

和往常一樣,這是更好地爲JSON的不錯的東西迴應:

responseText = { 
    "price": 50.00, 
    "link": '#something' 
}; 

上面的PHP是輸出時,它會是:

<?php header ("Content-type: application/json"); ?> 
{ 
    "price": 50.00, 
    "link": '#something' 
} 

而且你可以使用它作爲:

document.getElementById('price').innerHTML = responseText.price; 
document.getElementById('price').setAttribute("href", responseText.link); 

既然你已經添加,我想加入這個信息將使這個答案值得。我不確定你是如何調用AJAX函數的,但這樣調用真棒。 jQuery的有一個內置的AJAX功能,您可以使用:

$.post("path/to/php", {data: to_be_sent}, function (responseText) { 
    responseText = JSON.parse(responseText); 
    $("#price").attr("href", responseText.link).html(responseText.price); 
}); 

閱讀是在這種情況下更容易:

$("#price").attr("href", responseText.link); // Gives you the #something 
$("#price").html(responseText.price);  // Gives you the 50.00 
+1

'使它通過使用HTML href'工作哦,所以現在我明白了這個問題;)我猜測OP想獲得href屬性 –

+0

我增加了更多點@A.Wolff,因爲OP的問題並不清楚! –

相關問題