[英]Passing data from javascript to PHP via POST not working
Im trying to send an array, populated using javascript on client-side, to a php file in the backend.我试图将在客户端使用 javascript 填充的数组发送到后端的 php 文件。
MAIN.JS主文件
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP门票.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:执行这个,我得到这个结果:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.我不明白为什么我会得到一个未定义的索引。 I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
我尝试使用谷歌搜索这个,但大多数响应似乎都指向使用某种 HTTPS 方法的方向,这就是我试图通过 POST 实现的目标。 Any help will be greatly appreciated.
任何帮助将不胜感激。 Thank you.
谢谢你。
The 'list' undefined issue might be due to the structure of the JSON array you pass. 'list' 未定义问题可能是由于您传递的 JSON 数组的结构造成的。
Try the below code and check if it works.尝试下面的代码并检查它是否有效。 If not let's check further :)
如果没有,让我们进一步检查:)
var list = {'list': iterateItems()}; _ajax("https://127.0.0.1/prog1/final/class/ticket.php", list) .done(function(list){}); }); function _ajax(url,data) { var ajax = $.ajax({ type : "POST", datatype : "json", url : url, data : data }) return ajax; } function iterateItems() { // array is an array populated in this function, returned to be sent to ticket.php return JSON.stringify( array ); };
Your PHP Code:您的 PHP 代码:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. PHP 无法自动解析 JSON 参数。
$_POST
will only be filled in from a URL-encoded string or a FormData object. $_POST
只会从 URL 编码的字符串或 FormData 对象中填充。
$.ajax
will URL-encode an array automatically for you. $.ajax
将自动为您对数组进行 URL 编码。
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode()
.在 PHP 中,您不需要调用
json_decode()
。 The value of $_POST['list']
will be the array. $_POST['list']
将是数组。
after you call var list = iterateItems();
在调用
var list = iterateItems();
add this list = 'list=' + list;
添加此
list = 'list=' + list;
the php file would then recognize the index list. php 文件然后会识别索引列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.