【问题标题】:Ajax passing data to php scriptAjax 将数据传递给 php 脚本
【发布时间】:2011-07-21 20:19:52
【问题描述】:

我正在尝试将数据发送到我的 PHP 脚本以处理一些内容并生成一些项目。

$.ajax({  
    type: "POST",  
    url: "test.php", 
    data: "album="+ this.title,
    success: function(response) {
        content.html(response);
    }
});

在我的 PHP 文件中,我尝试检索专辑名称。虽然当我验证它时,我创建了一个警报来显示 albumname 是什么我什么也没得到,我尝试通过 $albumname = $_GET['album']; 获取专辑名称

虽然它会说未定义:/

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    您正在发送 POST AJAX 请求,因此请在您的服务器上使用 $albumname = $_POST['album']; 来获取值。另外,我建议您编写这样的请求以确保正确编码:

    $.ajax({  
        type: 'POST',  
        url: 'test.php', 
        data: { album: this.title },
        success: function(response) {
            content.html(response);
        }
    });
    

    或更短的形式:

    $.post('test.php', { album: this.title }, function() {
        content.html(response);
    });
    

    如果您想使用 GET 请求:

    $.ajax({  
        type: 'GET',
        url: 'test.php', 
        data: { album: this.title },
        success: function(response) {
            content.html(response);
        }
    });
    

    或更短的形式:

    $.get('test.php', { album: this.title }, function() {
        content.html(response);
    });
    

    现在您可以在您的服务器上使用$albumname = $_GET['album'];。不过要小心 AJAX GET 请求,因为它们可能会被某些浏览器缓存。为避免缓存它们,您可以设置 cache: false 设置。

    【讨论】:

    • 感谢这对我使用 GET 有用。无法解决这个问题:/ 非常感谢!
    • $.get('test.php', { album: this.title } 我想问如何发送两个值
    • @M.chaudhry 你可能已经找到了这个,但对于未来的读者来说,这是JSON,所以要发送多个值,你只需用逗号添加另一个值:$.get('test.php', { album: this.title, song: that.title });
    【解决方案2】:

    尝试像这样发送数据:

    var data = {};
    data.album = this.title;
    

    然后你就可以像访问它了

    $_POST['album']
    

    注意不是“GET”

    【讨论】:

      【解决方案3】:

      您也可以使用下面的代码通过 ajax 传递数据。

      var dataString = "album" + title;
      $.ajax({  
          type: 'POST',  
          url: 'test.php', 
          data: dataString,
          success: function(response) {
              content.html(response);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-03
        • 2013-06-18
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-14
        相关资源
        最近更新 更多