使用PHP,jsonp,jquery实现跨域

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

</body>
<script>
  $(function () {
    $.ajax({
        url: "http://localhost/php/select_data.php",
        type: "post",
        data: {id: "id"},
        dataType: "jsonp",
        jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
        jsonpCallback: "success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
        success: function (data) {
          for(let i in data){
            console.log(eval("(" + data[i] + ")"))
          }
        },
        error: function (error) {
          console.log("error", error)
        }
      }
    )
  })
</script>
</html>

  PHP代码:

<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2017/12/8
 * Time: 14:31
 */
$callback = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : ''; //jsonp回调参数,必需
function getKey($key,$default=""){
    return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default);
}
$id = getKey("id");
$conn = mysqli_connect("localhost","root","","test") or die("连接失败");
$conn->query("set names utf8");
$sql = "select * from data where ".$id." is not null";
$result = $conn->query($sql);
$arr = [];
while($row=$result->fetch_assoc()){
    array_push($arr,json_encode($row));
}
$json = json_encode($arr);  //json 数据
echo $callback.'('.$json.')';  //返回格式,必需

  效果如下:

 

posted @ 2017-12-11 10:41  明明一颗大白菜  阅读(332)  评论(0编辑  收藏  举报
<-- -->