【问题标题】:Undefined PHP output from ajax call来自 ajax 调用的未定义 PHP 输出
【发布时间】:2020-03-10 02:48:47
【问题描述】:

我希望通过 TCPDF 通过 ajax 创建 PDF 文件。一切正常,PDF 保存在服务器中我将 URL 传递给我的 HTML

$responseArray = array('id' => 'Success', 'message1' => 'Hello', 'message2' => '/pdfgen/genpdf/'.$filetitle.'.pdf');
$encoded = json_encode($responseArray);             echo $encoded;

然后我得到重定向。问题是虽然我的浏览器控制台选项卡显示 PHP 发送的内容是

{"id":"Success","message1":"Hello","message2":"/pdfgen/genpdf/1703419677.pdf"}

返回 HTML 文件,我无法将 URL 分配给变量。

它只是打印 undefined。

$.ajax({
    type: 'POST',
    url: "path to php",
    data: ({mob: mob}),
    dataType: 'json',
}).done(function(data) {
    console.log(data);
    var id = data.id;   
    var message1 = data.message1;
    var message2 = data.message2;
});

【问题讨论】:

  • 您将值作为数据返回,并尝试分配为 response.id。使用数据更改响应:var id = data.id
  • 你必须像这样设置标题: header('Content-Type: application/json');并且JS文件有错误,你必须使用data.id而不是response.id
  • 您的回调有参数data,但您尝试使用response??
  • @Sfili_81 都是响应,但我在试错过程中更改为数​​据。我现在统一了它,仍然是同样的问题。
  • @RaminRezazadeh 我尝试设置标头,但后来我遇到了另一个问题,说您无法再次发送标头,因为 TCPDF 通过静态文件发送标头

标签: php ajax tcpdf


【解决方案1】:

只需将数据替换为响应

$.ajax({
        type: 'POST',
        url    : "path to php",
        data: ({mob: mob}),
        dataType: 'json',
        })
.done(function(response) {
        console.log(data);
        var id = response.id;   
        var message1 = response.message1;
        var message2 = response.message2;
        alert(message2 );
        });

【讨论】:

  • 请用适当的标签格式化您的答案。并给出一些解释,请您的回答如何提供帮助
【解决方案2】:

将您的代码response.idresponse.message1response.message2 替换为
data.id, data.message1 and data.message2。因为你在成功函数中使用了data

【讨论】:

    【解决方案3】:

    希望帮助:

    $.ajax({
        type: 'POST',
        url: "path to php",
        data: ({mob: mob}),
        dataType: 'json',
    }).done(function(response) { <-- edit
        console.log(response); <-- edit
        var id = response.id;   
        var message1 = response.message1;
        var message2 = response.message2;
        alert(message2);
    });
    

    【讨论】:

      【解决方案4】:
      $.ajax({
          url: 'path to php',
          type: 'post',
          data: {mob: mob},
          dataType: 'json',
          success: function(response) {
              console.log(response); 
          }
      });
      

      【讨论】:

      • 对于遇到同样问题的人。请说明此答案如何解决您的问题
      猜你喜欢
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多