【发布时间】: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