2012-06-01 16 views
1

我有一個包含Ajax,PHP和Javascript的頁面。在該頁面上,我有一個選擇/組合框的網站。當用戶選擇一個網站時,我調用了一個使用Ajax和GET方法發送到PHP文件並執行PHP代碼的JavaScript函數。那個PHP文件,我已經連接到一個數據庫(使用用戶網站選擇來拉一個特定的行)。然後我想發送一些存儲在數據庫中的細節(關於用戶選擇的網站)並在頁面上使用它們來運行其他PHP代碼。Ajax,PHP,Javascript在組合框選擇後從數據庫提取值

我似乎無法讓它與我有的代碼一起工作,我試過了我能想到的一切。

選擇框代碼中調用javascript函數:

<select name="website" onchange="doSomething(this.value)" /> 
<option>option 1</option> 
<option>option 2</option> 
<option>etc.</option> 
</select> 

使用Ajax調用PHP文件JavaScript函數:

function doSomething(str) 
{ 
if (str == "") 
{ 
document.getElementById("DIVdisplayID").innerHTML="Nothing Selected"; 
return; 
} 
if (window.XMLHttpRequest) 
{// code for IE7+, Firefox, Chrome, Opera, Safari 
xmlhttp=new XMLHttpRequest(); 
} 
else 
{// code for IE6, IE5 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
xmlhttp.onreadystatechange=function() 
{ 
if (xmlhttp.readyState==4 && xmlhttp.status==200) 
{ 
    document.getElementById("DIVdisplayID").innerHTML=xmlhttp.responseText; 
} 
} 
xmlhttp.open("GET","URLHERETOPHPFILEHERE?website="+str,true); 
xmlhttp.send(); 

} 

我的顯示DIV:

<div id="DIVdisplayID"></div> 

PHP文件訪問數據庫的信息基於關閉的網站用戶選擇:

<?php 
$website=$_GET["q"]; 

$con = mysql_connect("localhost","username","password"); 
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("database", $con); 

$result = mysql_query("SELECT * FROM Websites 
WHERE WebsiteURL='$website'"); 

while($row = mysql_fetch_array($result)) 
{ 
echo $row['WebsiteDetail1'] . " " . $row['WebsiteDetail2']; 
echo "<br />"; 
} 

mysql_close($con); 
?> 

回答

0

jQuery的。

doSomething(this.value)不起作用。

doSomething(this.options[this.selectedIndex].text)) 

doSomething($(this).val())使用jQuery

所有的JavaScript可以

$.get("URLHERETOPHPFILEHERE?website="+str, function(data){ 
    $('#DIVdisplayID').html(data); 
}); 

我假設改爲 「URLHERETOPHPFILEHERE」 實際上是在你的代碼代替。

+0

^試過這個,我似乎無法得到它的工作。 – user1431639

0

替換您此行的代碼:

xmlhttp.open("GET","your php file name with .php extension ?website="+str,true); 

和PHP文件,你可能是使用GET方法使用GET方法 「網站」 的名字:

xmlhttp.open("GET","URLHERETOPHPFILEHERE?website="+str,true); 

替換爲 像:

$website=$_GET["website"]; 
+0

^我很困惑,那正是我所擁有的。 – user1431639

+0

你在上面的代碼中遇到問題嗎? – Harshal

相關問題