我有一个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。我不确定我在这里做错了什么。
EDIT:不管是否将字符串转换为json,这都是一样的天气。
因此,输入仅包含文本名称。
string关键字
不要使用"string"关键字。
评估
埃瓦尔是邪恶的——小心使用。
严格模式
确保始终在"严格模式"下工作,将这一行放在代码的开头:
'use strict'
构建响应对象
您不必手动粘贴您的帖子对象。就这样做吧:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
避免使用不必要的语法。
$.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
}
});
您需要从php://input如果您不使用多部分/表单数据,那么application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
如果您将其作为json发送,那么您的$_POST变量将继续为NULL,除非您这样做。