自己給自己寫介面
阿新 • • 發佈:2019-01-04
工具:
XAMPP 3.2.2(Apache+MySQL+PHP);
navicat for mysql
伺服器:
阿里雲/新浪雲/百度應用/京東雲
index.php
<?php
//jsonp回撥引數
$callback = isset($_GET['callback']) ? trim($_GET['callback']) : '';
//設定跨域請求頭
header('Access-Control-Allow-Origin:*');
//建立例項
class Person {
public $userName;
public $age;
public $resume ;
public $userAccount;
public $password;
function __construct( $_userName, $_age, $_resume, $_userAccount, $_password)
{
$this->userName = $_userName;
$this->age = $_age;
$this->resume = $_resume;
$this->userAccount = $_userAccount;
$this ->password = $_password;
}
}
$arr = array(
'code'=>'400',
'message'=>'Insert In Error'
);
//連線資料庫
$conn = mysql_connect('127.0.0.1', 'root', '') or die('Error Info : '.mysql_error());
mysql_select_db('db_mxd', $conn);
$result_sql = mysql_query("select * from dong") or die('Error Info_1' .mysql_error());
$row = mysql_fetch_object($result_sql);
//拼接字串
$result = array();
do{
$obj = new Person($row->userName, $row->age, $row->resume, $row->userAccount, $row->password);
array_push($result, $obj);
}while($row = mysql_fetch_object($result_sql));
if(count($result) > 0)
{
$arr['code'] = '200';
$arr['message'] = 'Success';
$arr['result'] = $result;
}else{
$arr['result'] = $result;
}
//關閉結果集
mysql_free_result($result_sql);
//關閉MySQL伺服器
mysql_close($conn);
//echo
$tmp= json_encode($arr);
echo $callback.'('.json_encode($arr).')';
?>
//index.html
jQuery.ajax({
url: "http://116.196.73.253/dong/index.php",
type: "get",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback:"success_jsonpCallback",
success: function (res) {
console.log(res)
$(".res").text("正確"+JSON.stringify(res))
},
error: function (e) {
console.log(e)
$(".res").text("錯誤"+JSON.stringify(e))
}
});
新建資料庫 db_mxd
新建表 dong
DROP TABLE IF EXISTS `dong`;
CREATE TABLE `dong` (
`id` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
`age` varchar(255) DEFAULT NULL,
`resume` varchar(255) DEFAULT NULL,
`userAccount` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of dong
-- ----------------------------
INSERT INTO `dong` VALUES ('1', '2', '3', '4', '5', '6');
跨域問題:
jQuery.ajax({
url: "http://xxxxx/MessageBoard/addMes.php",
type: "get",
dataType: "jsonp",
jsonp: "callback",
success: function (res) {
console.log(res)
$(".res").text("正確"+JSON.stringify(res))
},
error: function (e) {
console.log(e)
$(".res").text("錯誤"+JSON.stringify(e))
}
});
<?php
$data = "今天你見彭于晏了嗎";
$callback = $_GET['callback'];
echo $callback.'('.json_encode($data).')';
exit;
?>