如何在JavaScript中调用PHP函数?

前端之家收集整理的这篇文章主要介绍了如何在JavaScript中调用PHP函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有

的index.PHP

<select id="year_list" name="year_list" onchange="check_year_event('year_list','event_list');" > . . .  </select>

<select id="event_list" name="event_list" onchange="check_year_event('year_list','event_list');" > . . . </select>
.
.
.
<?PHP 
 function checkYearandEvent($year,$event) {
  $year_event = MysqL_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")

  if (MysqL_num_rows($year_event) > 0) {
   // do this
  }

 }
?>

myscripts.js

function check_year_event(year_id,event_id) {
 var year = document.getElementById(year_id).value;
 var event = document.getElementById(event_id).value;

 // call PHP function (but I don't know how): checkYearandEvent(year,event);

}

我的问题是每当用户更改任何select元素的值时,如何调用PHP函数.

解决方法

你需要使用ajax.有一个基本的例子:

myscripts.js

function AjaxCaller(){
    var xmlhttp=false;
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }

    if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function callPage(url,div){
    ajax=AjaxCaller(); 
    ajax.open("GET",url,true); 
    ajax.onreadystatechange=function(){
        if(ajax.readyState==4){
            if(ajax.status==200){
                div.innerHTML = ajax.responseText;
            }
        }
    }
    ajax.send(null);
}

function check_year_event(year_id,event_id) {
 var year = document.getElementById(year_id).value;
 var event = document.getElementById(event_id).value;

    callPage('file.PHP?year='+year+'&'+'event=+'+event,document.getElementById(targetId));
}

file.PHP

<?PHP 

     function checkYearandEvent($year,$event) {
      $year_event = MysqL_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")

      if (MysqL_num_rows($year_event) > 0) {
       // do this
      }

     }
    echo checkYearandEvent($_GET['year'],$_GET['event']);
?>

猜你在找的JavaScript相关文章