![](/img/trans.png)
[英]Javascript global error handling via AJAX/PHP: limit logs to my own script
[英]AJAX / PHP error handling and global variable
这是我第一次写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已打开。
不,这有一些问题:
key
,因此您将需要$_POST['key']
在您的php脚本中; .preventDefault()
。 在这种情况下,您需要从事件处理程序中获取event
变量: $('button').on('click', function(event) {
。 data: $('form').serialize()
轻松发送所有键值对: data: $('form').serialize()
。 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.';
?>
这是这样做的方法:
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.';
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.