这是我第一次在下面写一个ajax是我的结构
submitted.php
<?php $a = $_POST['a']; // an input submitted from index.php ?>
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php echo $a; // will this work? ?>
ajax返回空白...没有错误,我的error_reporting已打开。
答案 0 :(得分:2)
不,这有一些问题:
key
的键 - 值对,因此您需要在PHP脚本中使用$_POST['key']
; .preventDefault()
。如果是这种情况,您需要从事件处理程序中获取event
变量:$('button').on('click', function(event) {
。data: $('form').serialize()
轻松发送所有键 - 值对。答案 1 :(得分:1)
form.php的
<button>bind to jquery ajax</button> <!-- ajax trigger -->
<span></span> <!-- return ajax result here -->
<script>
// NOTE: added event into function argument
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function(msg) {
$('span').html(msg);
});
});
</script>
process.php
<?php
echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';
?>
答案 2 :(得分:1)
这是做到这一点的方法:
ubmitted.php
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
// no need to prevent default here (there's no default)
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php的
<?php
if (isset($_POST['key'])
echo $_POST['key'];
else echo 'no data was sent.';
?>