Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从javascript脚本调用php函数_Javascript_Php_Ajax - Fatal编程技术网

从javascript脚本调用php函数

从javascript脚本调用php函数,javascript,php,ajax,Javascript,Php,Ajax,我有一个文件,我把所有需要的函数放在那里。我需要的是这个: //the functions file //........ function user_exists($username){ $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') FROM users WHERE username = '$username'"); return (mysql_result(

我有一个文件,我把所有需要的函数放在那里。我需要的是这个:

//the functions file
//........
function user_exists($username){
    $username = sanitize($username);
    $query = mysql_query("SELECT COUNT('user_id') FROM users WHERE username = '$username'");
    return (mysql_result($query, 0) == 1) ? true : false;
}
?>
我已经在register.php文件中包含了函数文件。我要做的是从javascript调用该函数:

//the register file (functions file is included here)
<script>
 //.....
      if(user_exists(element.value)){  ........   }
 //.....
</script>
//寄存器文件(此处包含函数文件)
//.....
如果(用户_存在(element.value)){……。}
//.....

我认为这可以用ajax解决,但既然我不熟悉它,该怎么做呢

您需要从PHP页面中调用PHP函数并打印结果。然后使用Javascript/AJAX连接到它,以获得PHP打印的纯文本。例如


函数loadXMLDoc(){
var-xmlhttp;
var反应;
if(window.XMLHttpRequest){
xmlhttp=新的XMLHttpRequest();
}
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
response=xmlhttp.responseXML;
警报(响应);
}
}
open(“GET”,“register.php”,true);
xmlhttp.send();
}

ajax。你的目标。你真的想要一个AJAX教程吗?或者有人将代码交给您?如上所述,这需要ajax请求:)我非常感谢代码中的帮助,以了解我在处理什么。分配事件,将ajax请求发送到服务页面,在服务页面上调用此函数,返回响应并取回。简单。
<script>
function loadXMLDoc(){
  var xmlhttp;
  var response;
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      response=xmlhttp.responseXML;
      alert(response);
    }
  }
  xmlhttp.open("GET","register.php",true);
  xmlhttp.send();
}
</script>