使用ajax发帖不起作用

Posting with ajax not working

本文关键字:不起作用 ajax 使用      更新时间:2023-09-26

所以我有一个这样的表单:

 <form>
     <input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" />
 </form>

和一个类似的函数:

<script type='text/javascript'>
function ConfirmChoice(theid) 
{ 
    var dataString = 'id=' + theid;
    answer = confirm("Are you sure you want to delete this song?");
    if (answer !=0) {
        $.ajax
        ({
            type: "POST",
            url: "deleteSong.php",
            data: dataString,
        });
    } 
}
</script>

所以基本上,我希望它从我的数据库中删除他们点击的任何内容,deleteSong将负责这些内容。它给出了歌曲的id,据我所知,应该确认删除,然后删除它,对吗?如有任何帮助,我们将不胜感激。感谢

将其从更改

input type="submit"

input type="button"

此外,因为您没有设置它,所以对服务器的请求是json格式的,在您的情况下,json格式不正确。

试试这样的东西:

 var dataString = "{'id'= '"+ theid + "'}";

这应该使它工作:)

如果不知道问题的确切位置,很难回答这个问题。deleteSong.php工作正常吗?

正如其他人所说,您应该将输入类型更改为button或从函数中返回false,否则浏览器将尝试以正常方式提交表单,但由于您没有在<form>标记中指定action,因此无法正常工作。

就我个人而言,我会采取完全不同的做法:

HTML:

 <input type="button" value="<?php echo $id ?>" id="deleteButton">

Javascript:

 $(document).ready(function () {
     $('#deleteButton').click(function () {
         var answer = confirm("Are you sure you want to delete this song?");
         if (!answer) {
             return false;
         }
         var data = 'id=' + $(this).val();
         $.ajax({
             type: 'POST',
             url: 'deleteSong.php',
             data: dataString,
             success: function (response) {
                 // response will contain the output from your php script.
                 // Do something with it here. If you just want to see what it
                 // says, do something like:
                 console.log(response);
                 // then look in the console (view > javascript console in chrome)
             }
         });
     });
});

只是为了解释我在这里做什么(很抱歉,如果我告诉你你已经知道的事情,我想对未来可能读到这篇文章的人尽可能明确:)

  • 我将整个内容包含在$(document).ready(function() { ... } );中,这样它只有在页面加载完成时才能运行,否则您可能会尝试将函数绑定到一个尚不存在的按钮上的单击操作
  • if (answer !=0)是多余的,您可以只写if (!answer),因为任何正整数都将计算为true
  • 我在上面包含了一个success回调,它可能会帮助您进行调试

整个页面上是否只有一个"删除"按钮?还是每首歌旁边都会有一个删除按钮?如果是后者,则必须为每个按钮指定不同的ID,而不仅仅是deleteButton,因为所有ID都必须是唯一的。

如果以上不起作用,你确定jQuery加载正确吗?要进行检查,请在控制台中键入jQuery,如果您没有收到错误,那么您就可以了。另一种可能是你的deleteSong.php脚本出了问题,但我不能在没有看到它的情况下帮你。