我有一個(可能是超級簡單的)問題。下面的代碼應該是_POST(使用AJAX)一個名爲'id'的變量到名爲getYourData.php的外部文件。將變量傳遞給外部PHP文件
我認爲這個問題在下面。 'data'部分似乎不起作用 - 我甚至試着把[data:'2']簡單地放在SELECT語句中'2'。但這甚至不起作用。
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: 'id',
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
這裏的代碼的其餘部分(片段 - jQuery的已導入)
<!-- First Box: click on link shows up second box -->
<div id="selectOne" style="float: left; margin-right: 10px; border: #666 thin solid; padding: 10px;">
<a href="#" id="1">One</a><br />
<a href="#" id="2">Two</a><br />
<a href="#" id="3">Three</a>
</div>
<!-- Second Box: initially hidden with CSS "display: none;" -->
<div id="selectTwo" style="float: left; margin-right: 10px; display: none; border: #666 thin solid; padding: 10px;"></div>
<!-- The JavaScript (jQuery) -->
<script type="text/javascript">
//Do something when the DOM is ready:
$(document).ready(function() {
//When a link in div with id "selectOne" is clicked, do something:
$('#selectOne a').click(function() {
//Fade in second box:
$('#selectTwo').fadeIn(500);
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: '2',
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
//Depending on the id of the link, do something:
if (id == 'one') {
//Insert html into the second box which was faded in before:
$('#selectTwo').html('One<br />is<br />selected')
} else if (id == 'two') {
$('#selectTwo').html('Two<br />is<br />selected')
} else if (id == 'three') {
$('#selectTwo').html('Three<br />is<br />selected')
}
});
});
</script>
getYourData.php - 創建一個基於從主頁面傳遞的 '身份證' 的自定義SELECT語句。出於某種原因,這是行不通的。只能當我故意設置一個啞炮變量($ ID2)
<?php
$username="primary";
$password="testpass";
$database="testdb";
mysql_connect(localhost,$username,$password) or die ('Unable to connect...');
mysql_select_db($database) or die('Error: '.mysql_error());
//Intentionally creating a dud variable will create a good SELECT statement and work
$id2 = "3";
$id = $_POST['id'];
$query = mysql_query('SELECT * FROM members WHERE member_id='.$id);
$result = mysql_fetch_assoc($query);
//Now echo the results - they will be in the callback variable:
echo $result['firstname'].', '.$result['lastname'];
mysql_close();
?>
您的AJAX函數中的'data'必須是'id = xxx'的形式。這是一個錯字嗎? –
@Andrew:但它是一個變量......它根據用戶點擊的id(鏈接)而變化。 xxx會是什麼? – Zakman411
@ Zakman441:我看到你在變量'id'中有它。試試''id ='+ id'。混淆我知道大聲笑 –