【发布时间】:2019-06-19 13:35:56
【问题描述】:
我一直在用这种简单的 javascript 和 php 通信将头撞到墙上。
我有一个要求用户输入两个数字的 HTML 表单。它应该将这两个数字作为 JSON 发送到服务器 (process.php)。在服务器中,它应该将两个数字相加并将结果发送回 JavaScript。之后,它将在 HTML 文件上打印结果。
javascript.js
$(document).ready(function(){
$('#calcular').click (function(e){
e.preventDefault();
var numerosJSON = JSON.stringify($('#myForm').serializeArray());
$.ajax({
url: '/process.php',
type:'post',
data: numerosJSON,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
contentType: 'application/json',
success: function(soma){
//shows result in a div in the html file
$('#out').text(soma);
}
});
});
})
process.php
$json = file_get_contents('php://input');
$numeros = json_decode($json, true);
$fst = $_POST['first'];
$snd = $_POST['second'];
$soma = $fst + $snd;
header('Content-Type: application/json, charset=utf-8');
echo json_encode($soma);
它确实发送了请求,但我总是收到错误:
致命错误:不能将 stdClass 类型的对象用作数组
你们能帮我解决这个问题吗?快把我逼疯了!
【问题讨论】: