【问题标题】:Cannot read the Ajax response returned by PHP file无法读取 PHP 文件返回的 Ajax 响应
【发布时间】:2020-04-15 22:10:47
【问题描述】:

我是 Ajax 的新手。

我无法从 PHP 文件中得到正确的响应。控制台中的答案是“未定义”。当我只是简单地处理 Response 变量时,控制台给了我对象;看来我无法获取 PHP 文件结果的值。

这是 HTML 代码:

<form id="form1" method="post" onsubmit="return send_form(this)">
        <p>Number 1= <input type="text" name="number1"></p>
        <p>Number 2= <input type="text" name="number2"></p>
        <input type="submit" value="calculate">

    </form>
        <script>
           function send_form(form1){
                    let response=$.ajax("1_1.php",{
                    dataType:'json',
                    data:{n1:form1.number1.value, n2:form1.number2.value},
                    }
                    );
                console.log(response.c);

                return false;
            }

        </script>

这是我的 PHP 文件

<?php

$a=$_GET['n1'];
$b=$_GET['n2'];
$c=$a+$b;

echo json_encode(['c'=>$c]);

?>

【问题讨论】:

  • 我的最佳建议:使用开发者工具。在 Network 面板中,您可以清楚地看到浏览器正在发送什么以及服务器如何响应;使用此信息来查看您的代码究竟是如何失败的。
  • 这是来自 PHP 文件的响应:{"c":38}。
  • @DevsiOdedra,我看过你的链接,但我的 PHP 响应实际上已经作为一个包含 1 个元素的数组发送
  • @Azamat 使用成功: ajax,从链接查看我的 ajax 代码

标签: javascript json ajax ajaxform


【解决方案1】:

似乎我不应该将 ajax 分配给变量。我试过这种方法,它奏效了:

function send_form(form1){
                    $.ajax("1_1.php",{
                    dataType:'json',
                    data:{n1:form1.number1.value, n2:form1.number2.value},
                    }
                    ).then(process);

                return false;
            }
            function process(result){
                console.log(result.c);
                return false;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多