我是ajax的新手,目前正在开发一个项目,需要将一些数据和ajax函数传递给php页面,以便动态创建和显示模态。我能够创建模态,但我认为我的问题在于没有正确地将数据传递给“test2.php”。我一直在努力获得正确的结果(我得到了我的错误信息),并希望有人可以提供帮助。
<body>
<?php echo $row['groupname'];
echo "<button class='btn btn-info btn-sm btn-circle' data-toggle='modal' data-target='#buttonModal' data-id='".$row['groupname']."' id='createButton'>+</button>";
echo "<div id='buttonModal' class='modal fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true' style='dispaly: none;'>";
?>
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add a Top Button</h4>
</div>
<div class="modal-body">
<div id"modal-loader" style="display: none; text-align: center;">
<!-- ajax loader -->
<img src="ajx-loader.gif">
</div>
<!-- msql data will be loaded here -->
<div id="dynamic-content"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" onClick="addRow('buttonTable')">Add Button</button>
<button type="button" name="Submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</div>
</body>
JQuery的:
$(document).ready(function(){
$(document).on('click', '#createButton', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
$('#dynamic-content').html(''); // leave this div blank
$('#modal-loader').show(); // load ajax loader on button click
$.ajax({
url: 'test2.php',
type: 'POST',
data: 'id=':+uid,
dataType: 'html'
})
.done(function(data){
console.log(data);
$('#dynamic-content').html(''); // blank before load.
$('#dynamic-content').html(data); // load here
$('#modal-loader').hide(); // hide loader
})
.fail(function(){
$('#dynamic-content').html('<i class="glyphicon glyphicon-info-sign"></i> Something went wrong, Please try again...');
$('#modal-loader').hide();
});
});
});
Test2.php:
<?php
require_once 'connectToServer.php';
//define variables
$groupName = "";
$buttonLinks = array("");
$buttonNames = array("");
$length = 0;
if (isset($_POST['id'])) {
$gpName = $_POST['id'];
}
?>
<div class="row">
<div class="col-sm-12">
<div class="form-group" id="groupName">
<label for="groupName">Group Name</label>
<input type="text" disabled class="form-control" name="groupName" value="<?php echo $gpName;?>">
</div>
<hr>
</div>
</div>
为了澄清,我收到的错误消息是“出错了,请再试一次......”并在ajax调用的.fail函数中指定。此外,更正数据:'id ='+ uid to data:{id:uid}仍会导致相同的错误。
答案 0 :(得分:2)
从数据键中删除冒号并正确编码数据本身
data: {id: uid}//properly encode the data to be passed to php script
答案 1 :(得分:0)
您可以通过更改data
字段来完成此操作。
$.ajax({
url: 'test2.php',
type: 'POST',
data: {id: uid},
dataType: 'html'
})