前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>职位查询</title>
<script src="jquery.js"></script>
</head>
<body>
<center><br><br>
<input type="text" id="val" ><input type="button" id="dian" value="查询"><br><br>
<div id="list" style="width:300px;border:1px #000 solid;height:200px"></div></center>
<script>
var url='http://www.nine.com/invite/frontend/web/index.php?r=index/jsonp';//接口路径
//var url='jsonp.php';
$("#dian").click(function(){
var zhi=$("#val").val();
var data={zhi:zhi};//搜索值
$.get(url,data,function(msg){
//console.log(msg);
//alert(msg[0].p_name);
var html='职位:';
for (var i in msg) {
//将接到的jsonp数据进行遍历
html+='<br /> '+msg[i].p_name;
};
$('#list').append(html);
},'jsonp')//指定数据为jsonp
})
//下面的方法也可以 为原生的ajax方法
/*$("#dian").click(function () {
var zhi=$("#val").val();
$.ajax({
url: url,
data:'zhi='+zhi,
dataType: "jsonp",
jsonpCallback: "aa",
success: function (msg) {
//console.log(data)
$('#list').append('职位:'+msg[0].p_name);
}
})
})*/
</script>
</body>
</html>
后端:
//jsonp 接口 查询职位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>职位查询</title>
<script src="jquery.js"></script>
</head>
<body>
<center><br><br>
<input type="text" id="val" ><input type="button" id="dian" value="查询"><br><br>
<div id="list" style="width:300px;border:1px #000 solid;height:200px"></div></center>
<script>
var url='http://www.nine.com/invite/frontend/web/index.php?r=index/jsonp';//接口路径
//var url='jsonp.php';
$("#dian").click(function(){
var zhi=$("#val").val();
var data={zhi:zhi};//搜索值
$.get(url,data,function(msg){
//console.log(msg);
//alert(msg[0].p_name);
var html='职位:';
for (var i in msg) {
//将接到的jsonp数据进行遍历
html+='<br /> '+msg[i].p_name;
};
$('#list').append(html);
},'jsonp')//指定数据为jsonp
})
//下面的方法也可以 为原生的ajax方法
/*$("#dian").click(function () {
var zhi=$("#val").val();
$.ajax({
url: url,
data:'zhi='+zhi,
dataType: "jsonp",
jsonpCallback: "aa",
success: function (msg) {
//console.log(data)
$('#list').append('职位:'+msg[0].p_name);
}
})
})*/
</script>
</body>
</html>
后端:
//jsonp 接口 查询职位
-
- public function actionJsonp()
- {
- header("Access-Control-Allow-Origin: *");//同源策略 跨域请求 头设置
- header('content-type:text/html;charset=utf8 ');
- //获取回调函数名
- $jsoncallback = htmlspecialchars($_REQUEST['callback']);//把预定义的字符转换为 HTML 实体。
- $zhi = htmlspecialchars($_REQUEST['zhi']);
- $arr=yii::$app->db->createCommand("select * from position where p_name like :name",array(':name'=>"%$zhi%"))->queryAll();//用的like进行模糊查询
- $json_data=json_encode($arr);//转换为json数据
- //输出jsonp格式的数据
- echo $jsoncallback . "(" . $json_data . ")";
- }
- 复制自https://blog.csdn.net/json_ligege/article/details/51505481
- https://www.cnblogs.com/jkko123/p/6294624.html 讲解的也很好