【问题标题】:How to send variables to php file with jquery/ajax and then echo the php to index (no alert)如何使用 jquery/ajax 将变量发送到 php 文件,然后将 php 回显到索引(无警报)
【发布时间】:2019-11-30 06:13:35
【问题描述】:

我是这里的新手,我遇到了死胡同。

所以我创建了一个在 php 中绘制日历的函数。而且我一直在使用 css 来设置日子的颜色和那些东西。该函数运行良好并使用 2 个输入变量,如下所示:

PHP 文件(calendar.php):

<?php
function draw_calendar($month,$year)
{
// the code
}
echo draw_calendar($current_month,$current_year);
?>

我一直在尝试做的是使用 jquery/ajax(来自我的索引文件)将变量发布/获取到 calendar.php 以供 $current_month 和 $current_year 使用。然后以某种方式将该函数回显到我的索引中。对于我的生活,我无法做到这一点。我只能找到如何返回简单字符串并将它们提醒到我的索引。

【问题讨论】:

  • 请向我们展示您的 jquery ajax 尝试,以便我们对其进行调试。
  • 另外请描述draw_calendar()的回复是什么样子的。

标签: javascript php jquery css ajax


【解决方案1】:

我不确定你写了什么代码,但她是关于如何使用 ajax 发送所需变量的大致思路。

在您的索引文件上:

var month = "11"; //your month
var year = "2019"; //your year

$.ajax({
  type: "POST",
  url: "calendar.php",
  data: {month: month, year: year},
  dataType: "json",
  success: function(response){
    //if it is success
  },
  error: function(){
    //if it results in error
  }
});

在您的日历文件中:

$month = $_POST['month'];
$year = $_POST['year'];

【讨论】:

  • ...不要忘记来自 PHP 的响应现在需要进行 json 编码(因为您有 dataType: "json"
  • 确实如此。 echo json_encode() 我假设他们知道...
  • 有很多人是 PHP 新手,以及一般的 Web 开发新手,他们不知道这一点。当您写答案时,请记住您为未来的访问者写它就像为 OP 一样。 :-)
  • 这会将变量发送到 calendar.php。但我无法从 calendar.php 中获取函数以在之后回显到索引
  • 使用echo json_encode(yourData);,然后使用response从ajax函数访问它。
猜你喜欢
  • 2021-11-10
  • 2013-08-23
  • 2014-02-08
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多