[英]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.