记录:封装实现跨域的代码

客户端部分:




 
  script => 跨域


 

 

服务端部分:

$conn = mysqli_connect('localhost', '***', '*****', '***');

$query = mysqli_query($conn, 'select * from users');

while ($row = mysqli_fetch_assoc($query)) {
  $data[] = $row;
}

if (empty($_GET['callback'])) {
  header('Content-Type: application/json');
  echo json_encode($data);
  exit();
}

// 如果客户端采用的是 script 标记对我发送的请求
// 一定要返回一段 JavaScript
header('Content-Type: application/javascript');
$result = json_encode($data);

$callback_name = $_GET['callback'];

echo "typeof {$callback_name} === 'function' && {$callback_name}({$result})";
 

 

转载于:https://my.oschina.net/u/3848851/blog/1838325

你可能感兴趣的:(php,javascript)