调用基于按钮类名称的Ajax函数单击

时间:2014-07-15 12:56:37

标签: php jquery ajax

我在php中创建了几个图像按钮。我为所有人分配了一个共同的课程。当我调用基于按钮类名称的jquery函数时单击。这工作正常,但当我尝试调用ajax函数时,它不起作用。没有看到任何错误。

PHP创建一个按钮

function printpic($name, $picpath, $category, $pic)
{  
    $style = " margin=0px; background-color=transparent; border=none;";
    //$functionname= "selectedpic(this.id)";
    $functionname= "myCall(this.id);";
    $styleimage = "HEIGHT= 120  WIDTH= 120  BORDER=0";
    $eventimage1= "zoomin(this)";
    $eventimage2= "zoomout(this)";
    $btnclass="btnclass";   
    $j=0;
    $spa=0;
    $i=0;
    for($k=0; $k<4; $k++)
    {
        echo "<tr>";
        for($j=0; $j<4; $j++)
        {   
            echo"<td>"; 
            $btn= "btn".$category[$i];
            echo "<span id='" . $spa. "'>";
            echo "<button name='" . $btn. "'
            margin ='".$style."' 
            class='".$btnclass."'
            onClick='".$functionname."'
            >";

            echo "<img src='". $picpath[$i]."/".$name[$i]."' 
            id ='".$pic[$i]."'
            alt ='".$name[$i]."'
            .$styleimage.
            onMouseMove='".$eventimage1."'
            onMouseOut='".$eventimage2."'

            >";
            echo "</button >";
            $spa++;
            echo"</span>";
            echo"</td>"; 
            $i++;
        } // wfor

    echo "</tr>";
           }// for
         }      // end function
        ?>

Jquery + Ajax

$(document).ready(function(e) {
$('.btnclass').click(function() {

event = event || window.event; 
var target = event.target || event.srcElement; 
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;

$.ajax({

         url: "indexverification.php",
         type: "POST",          
         data: datastring,
         success: function(responseText) { // get the response
         if(responseText == 1) { alert ("hi");}
         else { alert (datastring); }

        } // end success            
        }); // ajax end



});

});

indexverification.php

<?php
  session_start();      
  $picno=$_SESSION['picno']; // picno from db
  $answer=$_SESSION['answer']; // answer from db
  $id=$_POST['id']; // id of picture clicked
  $ans=$_SESSION['ans']; // answer type


  if (($id==$picno) && ($answer==$ans))
 {
    echo '1';
 }

 else 
{
    echo '2';   
}
?>

1 个答案:

答案 0 :(得分:0)

我认为你使用了错误的语法。试试这个:

//AJAX request
$.ajax({
     url: "indexverification.php",
     type: "POST",          
     data: datastring,      
})
//Success action
.success(function( html ) {
    if(responseText == 1) { alert ("hi");}
    else { alert (datastring); };
}) 
//Error action
.fail(function() {
    alert("Request failed.");
});