发送带有对象的数组会将ajax抛出到php中
请帮帮我: 我创建我的对象:发送带有对象的数组会将ajax抛出到php中,php,json,ajax,Php,Json,Ajax,请帮帮我: 我创建我的对象: var data = []; $("#report-container [id^='report-']").each(function(index) { var reportObject = { "subject" : "", "photo" : "", "rating" : "", "comment" : "" }; reportObject.subject = $("#na
var data = [];
$("#report-container [id^='report-']").each(function(index) {
var reportObject = {
"subject" : "",
"photo" : "",
"rating" : "",
"comment" : ""
};
reportObject.subject = $("#name-report-"+index).text();
reportObject.photo = $("input[name='subject-photo-"+index+"']")[0].files[0];
reportObject.rating = $("input[name='subject-rating-"+index+"']").val();
reportObject.comment = $("textarea[name='subject-comment-"+index+"']").val();
data.push(reportObject);
});
在此之后,我有一个数组。我将其转换为json,如下所示:
var myarray = JSON.stringify(data);
[{"subject":"Окна","rating":"0","comment":""},{"subject":"Пол","rating":"0","comment":""}]
如果我将其记录下来,它看起来如下所示:
var myarray = JSON.stringify(data);
[{"subject":"Окна","rating":"0","comment":""},{"subject":"Пол","rating":"0","comment":""}]
然后我将其发送到php:
$.ajax({
type: "POST",
url: "/report-data/add_report.php",
data: { data: myarray },
async: true,
cache: false,
在php中,我尝试如下所示:
$data = json_decode($_POST["data"]);
echo(json_encode("this".$data));
但它不起作用 如果您尝试这段代码,您会发现php变量$data是一个数组() 那么在第二行你有
echo(json_encode("this".$data));
这导致了错误,因为您无法将字符串与数组连接起来“this”。$data
,所以请尝试以下简单更改
echo("this".json_encode($data));
因为
json_encode($data)
返回一个字符串,然后您可以将它与字符串“this”连接起来在ajax回调中放置一个success和一个error函数,查看哪个1被命中,还请显示来自网络选项卡的错误消息不起作用如何?echo(json_encode(“this”$data))代码>看起来很奇怪。你想在这里完成什么?我试图发送php接收到的内容,然后你只需执行var\u转储($\u POST)
并在dev consoles network选项卡中检查真正的响应。实际上,您正在使用json_encode()更改数据(因为您正在向其中添加内容)。