【问题标题】:How to access the form data from PHP ($_POST not working ??)如何从 PHP 访问表单数据($_POST 不起作用??)
【发布时间】:2019-07-18 15:52:53
【问题描述】:

我正在使用 $.post 方法将二维数组从 js 文件传递​​到 ajax.php 脚本。我的 .js 函数看起来像这样

function doSendEmail (aData) {
  var sData = JSON.stringify(aData)
  $.post('dd-ajax.php', { m: 'sendEmail', sData: sData },
    function () {})
    .done(function () { console.log('Done') })
    .fail(function (err) { showMessage(`unexpected error: ${err.responseText}`) })
    .always(function () { spinner(false) })
}

然后我的 Ajax.php 文件看起来像:

if ($method == "sendEmail") {
    $sData = array_key_exists('sData', $_POST) ? $_POST['sData'] : NULL;

    foreach($sData as $line) {
        $to = $line[7];
        $name = $line[0];
        $subject = 'Email Subject';
        $message = `Dear $name, Blah blah blah`;
        mail($to, $subject, $message);
    }
}

我在浏览器中的 headers > 表单数据中看到我的数据,但我似乎无法访问 Php 中的任何内容??

我试过上面的array_key_exists,也试过$_POST[sData],但没有任何乐趣。

我是新手,请善待

【问题讨论】:

  • 您发送的数据是什么样的?粘贴示例。
  • var_dump($_POST) 看看你的数据是什么样子的。
  • 我没有发现任何明显错误,但无法说出您的代码在哪里失败,因为它取决于许多具有未知值的变量。 aData 中有什么内容?执行什么回调?你得到什么状态码? $_POST 包含什么? $method 是什么?
  • 我的立场是正确的:如果$_POST['sData'] 是一个字符串,试图循环遍历它是不可能的。您是否已将 PHP 配置为显示错误消息?

标签: javascript php jquery post


【解决方案1】:

感谢 Alvaro 为我指明了正确的方向。 $method 在文件的前面被声明为 = 到 $_GET 中的“m”。添加if 已对其进行了排序。我猜是菜鸟的错误....还是谢谢

$method = array_key_exists('m', $_GET) ? $_GET['m'] : NULL;
if ($method == NULL) {$method = array_key_exists('m', $_POST) ? $_POST['m'] : NULL;}

【讨论】:

    【解决方案2】:
    data = { 'm': 'sendEmail', 'sData': sData };
     $.ajax({
            url: 'dd-ajax.php',
            type: 'POST',
            data: data,
            success: function (data) {
                console.log('Done');
            },
            error: function() {
                console.log("error");
            }
        });
    

    dd-ajax.php

    $method = $_POST['m'];
    if ($method == "sendEmail") {
        $sData = array_key_exists('sData', $_POST) ? $_POST['sData'] : NULL;
    
        foreach($sData as $line) {
            $to = $line[7];
            $name = $line[0];
            $subject = 'Email Subject';
            $message = 'Dear $name, Blah blah blah';
            mail($to, $subject, $message);
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2016-08-21
      • 2015-04-11
      相关资源
      最近更新 更多