2013-03-20 23 views
0

我想将ajax应用到我的php代码中。但是,当我点击按钮时,我无法得到任何回应。这意味着我声明的ajax函数不被称为onclick如何在php代码上应用ajax

<?php 
$s_name= $_POST["submit"]; 

mysql_connect("localhost","root","");//database connection 
mysql_select_db("itcompanylist"); 

$query = "SELECT s_id FROM states WHERE `state_name` = '$s_name'"; 
$result1 = mysql_query($query); 
$row = mysql_fetch_array($result1); 
$result2 = mysql_query("SELECT city_name FROM `city` WHERE s_id ='".$row['s_id']."'"); 

$i = 0; 

echo "<form method='post' name='myForm'><table border='1' ><tr>"; 

while ($row = mysql_fetch_row($result2)){ 
    echo '<td><input type="submit" name="submit" onclick="ajaxFunction()" value="'.$row['0'].'"></td>'; 

    if ($i++ == 2) 
    { 
    echo "</tr><tr>"; 
    $i=0; 
    } 
} 


echo "</tr></table></form>";  
echo "<div id='ajaxDiv'>Your result will display here</div>";  
?> 

Ajax代码:

<script language="javascript" type="text/javascript"> 
<!-- 
//Browser Support Code 
function ajaxFunction(){ 
var ajaxRequest; // The variable that makes Ajax possible! 

try{ 
    // Opera 8.0+, Firefox, Safari 
    ajaxRequest = new XMLHttpRequest(); 
}catch (e){ 
    // Internet Explorer Browsers 
    try{ 
     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
    }catch (e) { 
     try{ 
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
     }catch (e){ 
     // Something went wrong 
     alert("Your browser broke!"); 
     return false; 
     } 
    } 
} 

ajaxRequest.onreadystatechange = function(){ 
    if(ajaxRequest.readyState == 4){ 
     var ajaxDisplay = document.getElementById('ajaxDiv'); 
     ajaxDisplay.value = ajaxRequest.responseText; 
    } 
} 
var s1 = document.getElementById('submit').value; 

var queryString = "?submit=" + s1 ; 

ajaxRequest.open("GET", "" + 
           queryString, true); 
ajaxRequest.send(null); 
} 
//--> 
</script>  
+2

而'ajaxFunction()'的代码是...? – SeanWM 2013-03-20 13:32:32

+2

您正在使用[an **过时的**数据库API](http://stackoverflow.com/q/12859942/19068),并应使用[现代替换](http://php.net/manual/en/ mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com/)**,现代的API会使[防御]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己从。 – Quentin 2013-03-20 13:35:09

回答

2

你的提交按钮将提交表单和Ajax请求尚未处理完离开页面。

将您的事件处理程序绑定到表单的提交事件,并阻止默认操作。

function ajax(event) { 
    // Send Ajax request here 
    event.preventDefault(); 
} 
var frm = document.getElementsByName('myForm')[0]; // Better to use an ID. Don't write HTML 3.2 
frm.addEventListener('submit', ajax); 
+0

哪个想写在(事件)上的地方? – 2013-03-20 13:41:34

+0

@NikunjJagad - 你可以使用任何你喜欢的变量名,但'event'是一个很好的名字(因为函数收到的参数是[一个事件对象](http://www.w3.org/TR/DOM-Level- 2,活动/ events.html#活动,活动)) – Quentin 2013-03-20 13:51:06

0

使用onclick =“return ajaxFunction()”和event.preventDefault();以避免默认表单提交。