index.html代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--利用cdn添加js和css庫(kù) -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body style="text-align: center; padding: 100px;">
姓名: <input type="text" name="username" id="yourName" />
<button id="send">提交</button>
<br><br><br><br>
<div id="result">結(jié)果:</div>
</body>
<script type="text/javascript">
$(function () {
$("#send").click(function () {
var name = $("#yourName").val();
var data = "name="+name; //如果后臺(tái)是$_POST方法獲取數(shù)據(jù)婉商,那么一定要索引(例如:索引name)
$.ajax({
type: "POST",
url: "server.php", //同目錄下的php文件
data:"name="+name, // 等號(hào)前后不要加空格
success: function(msg){ //請(qǐng)求成功后的回調(diào)函數(shù)
$("#result").append("你的名字是"+msg);
}
});
})
})
</script>
</html>
server.php代碼
<?php
$username = $_POST['name'];//獲取索引值
echo $username;
?>
image.png
image.png
多參數(shù)
ajax
$.ajax({ url: 'insert2.php',
type: 'post',
data:{"content":temp,"time":times},
dataType:'text',
success: function()
{
alert("添加成功");
}});
php接收
$temp=$_POST['content'];
$time=$_POST['time'];
或者:
data: "name=John&location=Boston",
跨域訪問(wèn)
1.ajax接口數(shù)據(jù)類型:json與jsonp
1让蕾、json格式:
{
"message":"獲取成功",
"state":"1",
"result":{"name":"工作組1","id":1,"description":"11"}
}
2峦剔、jsonp格式:
callback({
"message":"獲取成功",
"state":"1",
"result":{"name":"工作組1","id":1,"description":"11"}
})
(1)前端代碼
$.ajax({
url: 'http://www.xxx.com/xxx/server.php',
async: false,
dataType: 'jsonp',
data: "name=" + name,
jsonp: 'callback', //Jquery生成驗(yàn)證參數(shù)的名稱
processData: false,
type: 'get',
success: function(data) {
// let a = JSON.parse(data);
console.log(data, $.type(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert(XMLHttpRequest.status);
// alert(XMLHttpRequest.readyState);
// alert(textStatus);
console.log(textStatus);
}
});
2.后端
<?php
function connDb(){
// 連接數(shù)據(jù)庫(kù).返回游標(biāo)
$odbc = "Driver={Microsoft Access Driver (*.mdb)};Dbq=".realpath("url.mdb");
$conn = odbc_connect($odbc, '', '', SQL_CUR_USE_ODBC);
return $conn;
}
$conn=connDb();
$sql ="select * from user";
$query = odbc_exec($conn, $sql);
$num = odbc_num_fields($query);
$callback=$_GET['callback'];
while ($row = odbc_fetch_row($query))
{
$data= $data.'{"urse":"'.odbc_result($query,"user").'","pwd":"'.odbc_result($query,"pwd").'"},';
}
$data=substr($data, 0, -1);
echo $callback."([".$data."])";
odbc_close($con);
?>