html、php和js值的传递(使用ajax进行传递)
在开发校企合作管理系统时,由于使用到了html、php和js之间的数据传递,所以这里记下此方法方便日后使用。
使用的场景:js获取checkbox的值后,将获取的值传递给php。
即:html(前端页面)->js->php(连接数据库,对数据库进行修改)
1.html
这里主要使用了弹出框来弹出所查询到的数据库因此做了两个table
<!--表格内容-->
<table id="qiye">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>合作企业名称</th>
<th>企业联系人</th>
<th>地址</th>
<th>所属行业</th>
</tr>
</thead>
<tbody>
<!--弹出框表格内容-->
<table style="font-family: '楷体';width: 770px">
<tr>
<td>合作企业名称</td>
<td><input type="text" id="newEnName"/></td>
<td>企业联系人</td>
<td><input type="text" id="newENlinkman"/></td>
</tr>
<tr>
<td>企业所属省份</td>
<td><input type="text" id="newEnprovince"/></td>
<td>企业地址</td>
<td><input type="text" id="newEnaddress"/></td>
</tr>
<tr>
<td>网址</td>
<td><input type="text" id="newEninternet"/></td>
<td>性质</td>
<td><input type="text" id="newEnqualit"/></td>
</tr>
<tr>
<td>所属行业</td>
<td><input type="text" id="newEnindustry"/></td>
<td>备注</td>
<td><input type="text" id="newEndetail"/></td>
</tr>
</table>
<div style="float: right;">
<button class="my-btn-gray" onclick="cancel()">取消</button>
<button class="my-btn-blue" onclick="save()">保存</button>
</div>
</table>
2.js获取html中的checkbox的值。
(需要注意的是getElementById/name要对应html的table名和checkbox名)
function getcheck(){
var rows = document.getElementById("qiye").rows;
var box = document.getElementsByName("check");
var states = "";
//var table = document.getElementById("qiye");
//获取勾选的所有值
for(var i=0;i<box.length;i++){
if(box[i].checked){
var row = box[i].parentElement.parentElement.rowIndex;
states += rows[row].cells[1].innerHTML+";";
//alert(rows[row].cells[1].innerHTML);
}
}
3.使用ajax将获取的值传递给php
(在这里需要注意的是html中需要调用jquery,同时由于php返回的数据为json格式因此这里需要将json数据解析给变量方便传递给html)
var table;
$.ajax({
type:'POST',
url:"../DB/searchDB.php",
data:{name:states},
success: function(data){
//alert("成功");
table=JSON.parse(data);
}
});
4.php
该php页面主要是连接数据库(DB.php)并查询数据库
<?php
require("../../DB.php");
$name=$_POST['EnName'];
$sql="select * from enterprise where EnName='$name'";
$res=$conn->query($sql);
if($res){
$table=$res->fetch_row();
}
$content=json_encode($table);
echo ($content);
//echo $table[0],$table[1];
?>
完整功能代码(实现了对数据库的修改):
链接:https://pan.baidu.com/s/1bLSwVL2t3A4KGKBGGNDNyg
提取码:qwpz