使用 AJAX 打开 php 文件


Using AJAX to open php file

所以我正在尝试打开更新数据库中某些内容的 af php 文件。我想使用 AJAX 执行此操作,因为我不希望更新整个页面。运行 php 文件后,我想更改触发 php 文件的页面上的图像。

这究竟是如何完成的?

希望你有jquery库

像这样做一个 AJAX 调用:

$('#upvote').click(function(){
    $.ajax({
        url : 'scripts/upvote.php', // give complete url here
        type : 'post',
        success : function(data){
            alert('success');
        }
    });
});

希望这对你有帮助

这是执行 AJAX 调用的一种方法。您实际上不需要将其设置为POST:

$.ajax({
    url: 'anyphpfile.php',
    dataType: 'type', //the type of data you're expecting
    success: function(result){
        //do what you want to update here
    }
});

何时执行此操作的结构取决于您进行 AJAX 调用的方式。 在标签中,你已经包含了jQuery,所以我假设你使用的是.ajax()函数。 现在,我将假设使用.then()回调(如果代码不同,请显示您的代码)。 在这种情况下,您将在此处"更改图像":

$.ajax({
  url: 'someurl.php'
}).then(function() {
  // change the image here
});

根据文档,.then()将始终在 AJAX 调用完成后调用。 您还可以使用其他更具体的功能,例如.done().fail()。 上面代码中的注释指示在何处执行响应 AJAX 调用的操作。 您执行的操作并不完全清楚。 你只是在改变img src吗? 像这样的东西,然后:

$('#theImage').prop('src', someUrlValue);

你从哪里得到someUrlValue取决于你。

如 JQuery 文档中所示:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function(result) {
    // Change image here
  },
  dataType: dataType
});

使用 jquery,简单地作为

$.ajax({url: "yourpage.php"});

查看参考以获取更多选项 http://api.jquery.com/jQuery.ajax/