javascript怎么调用php方法?

26次阅读
没有评论

在前端页面中调用后端的PHP方法,可以使用Ajax技术。Ajax是一种使用响应式网页设计的Web开发技术,可以帮助前端页面与后端PHP服务器交互。具体方法如下:

1.首先在前端页面中创建一个XMLHttpRequest对象

var xmlhttp;
if (window.XMLHttpRequest) {
  // code for modern browsers
  xmlhttp = new XMLHttpRequest();
} else {
  // code for old IE browsers
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

2.通过xmlhttp对象发送请求

var url = "test.php"; //PHP文件的URL
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();

3.处理后端返回的数据

xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    alert(this.responseText); //显示后端PHP方法返回的数据
  }
};

4.在后端PHP文件中编写对应的方法,并返回数据

test.php文件示例:

<?php
function hello() {
    return "Hello World!";
}

echo hello(); //返回值
?>

最终的完整示例:

test.html文件





AJAX Demo

test.php文件

<?php
function hello() {
    return "Hello World!";
}

echo hello(); //返回值
?>
正文完
 
评论(没有评论)