dongsheng8158 2013-03-20 13:29
浏览 17
已采纳

如何在php代码上应用ajax [关闭]

I am trying to apply ajax to my php code. However, when I click on the button I can't get any response. This means the ajax function I declare is not being called onclick.

<?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 code:

<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条回答 默认 最新

  • douzi5214 2013-03-20 13:37
    关注

    Your submit button will submit the form and leave the page before the Ajax request has been processed.

    Bind your event handler to the form's submit event, and prevent the default action.

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?