[英]Passing value to php script via Ajax
我在通过Ajax将值传递给我的php脚本时遇到问题,这是我的代码:
我通过href链接将值发送给ajax:
扫描目录后,我在href上获取文件链接:
<a href="" onclick="getfilename('<?php echo $file; ?>');"><?php echo $file; ?></a>
我的js函数接收值:
function getfilename(content) {
alert(content); // i can see my value here
$.ajax({ //not work
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert(response); //nothing
});
}
我的script.php
$album = $_POST['song'];
echo $album;
我不明白为什么它不起作用。
谢谢您的帮助!
尝试改变
<a href="" onclick="getfilename('<?php echo $file; ?>');"><?php echo $file; ?></a>
对此
<a href="#" onclick="getfilename('<?php echo $file; ?>');"><?php echo $file; ?></a>
也许您的页面在ajax数据加载之前正在刷新。
查看您的js代码,您的成功回调函数末尾缺少“}”。
// $file = 'teste';
<a href="#" onclick="getfilename('<?php echo $file; ?>');"><?php echo $file?></a>
function getfilename(content) {
alert(content);
$.ajax({
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert('Response: ' + response); //Alerts Result
}
});
}
// Script.php
<?php
echo $_POST['song']
?>
当您使用link元素时,它将在执行onclick事件后自动转到href中的位置。 将其保留为空将重新加载页面。
我建议您添加“ return false”; 作为onclick的最后一条指令。
<a href="" onclick="getfilename('<?php echo $file; ?>'); return false;"><?php echo $file?></a>
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.