[英]Ajax post - POST array is returning empty on server side
我有一个js函数,它正在收集数据并将其发送到php文件。
我正在尝试提交数组作为帖子的一部分:
函数send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
在提交我的PHP文件时,返回一个POST数组为NULL。 我不确定我在做什么错。
编辑:这是我尝试将字符串转换为json或不转换的相同天气。
另外,输入仅包含文本名称。
字符串关键字
不要使用“字符串”关键字。
评估
评估是邪恶的-请谨慎使用。
严格模式
通过将以下行放在代码开头,确保始终在“严格模式”下工作:
'use strict'
建立您的回应对象
您不必手动粘贴发布对象。 就是这样:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery正确的方法
避免弄乱不必要的语法。
$.post(url, post)
.done(function(response){
// your callback
});
结论
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
如果您未使用multipart / form-data,则需要从php:// input获取,因此,application / json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
如果您将其作为json发送,除非您这样做,否则$ _POST变量将继续为NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.