您需要在 pull-from.php 文件中添加一些代码(或创建另一个使用它来获取数据的文件),这些代码可以接受来自 AJAX 调用的参数并返回响应,最好是 JSON。这基本上就是您的网络服务。
下面是一个简单的例子,说明 php 基本上需要做什么。我包含了一个从 Web 服务获取数据并显示它的 html 页面。
<?php
$criteria = $_POST['criteria'];
function getData($params) {
//Call MySQL queries from here, this example returns static data, rows simulate tabular records.
$row1 = array('foo', 'bar', 'baz');
$row2 = array('foo1', 'bar1', 'baz1');
$row3 = array('foo2', 'bar2', 'baz2');
if ($params) {//simulate criteria actually selecting data
$data = array(
'rows' => array($row1, $row2, $row3)
);
}
else {
$data = array();
}
return $data;
}
$payload = getData($criteria);
header('Content-Type: application/json');//Set header to tell the browser what sort of response is coming back, do not output anything before the header is set.
echo json_encode($payload);//print the response
?>
HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample PHP Web Service</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function(){
alert("Lets get started, data from the web service should appear below when you close this.");
$.ajax({
url: 'web-service.php',
data: {criteria: 42},//values your api needs to query data
method: 'POST',
}).done(function(data){
console.log(data);//display data in done callback
$('#content').html(
JSON.stringify(data.rows)//I just added the raw data
);
});
});