[英]Nothing's in $_POST. Is there something wrong with my code?
我對JavaScript和PHP相當陌生,這是第一次遇到和使用JSON。 我認為我的AJAX請求很好,但是即使這樣, $_POST
數組還是空的。
這是AJAX調用:
$( "#submit" ).click( function() {
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
get_experience_data()
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
這是從表中獲取數據的函數:
function get_experience_data() {
var temp, data_exp = [];
$( "#exptable tbody tr" ).each( function() {
temp = {
company: $(this).find('td').eq(0).html(),
position: $(this).find('td').eq(1).html(),
datestart: $(this).find('td').eq(2).html(),
dateend: $(this).find('td').eq(3).html(),
description: $(this).find('td').eq(4).html()
};
data_exp = data_exp.concat(temp);
});
return data_exp;
}
作為參考,目標控制器函數僅打印$_POST
數組(通過我使用CodeIgniter的方式):
public function pass_basic_data() {
var_dump($_POST);
}
您能指出我犯的錯誤嗎,因為我找不到它。 非常感謝!
更新:我特別收到此消息:
array(1) {
["undefined"] =>
string(0) ""
}
更新:
感謝所有的幫助! 我已經解決了 它使我到處跳舞。 我將返回值包裝在{name : value}
對中。
$( "#submit" ).click( function() {
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
{object: post_vars}
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
我建議從以下步驟開始:
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
嘗試這個:
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
// you need to add parentheses here --------------------------------------------------^
當您將函數傳遞給$.post()
它將假定它是一個在收到響應后將被調用的回調。 您要做的就是調用該函數並將其返回值傳遞給$.post()
。
順便說一句,這行:
data_exp = data_exp.concat(temp);
可以替換為:
data_exp.push(temp);
如果只是在最后添加一個值,則不必每次都創建一個新數組。
您需要執行方法get_experience_data,否則您將傳遞不執行它的函數
嘗試對實際的jquery(而不是php部分)進行故障排除。 但是這是一個建議:
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data', post_vars );
這是我以前的答案加上注釋的結論,但是我仍然不確定是否可以將數組中的數組隱式化。
var submit_basic = $.ajax({
type: "POST",
url: 'index.php/submit_data/pass_basic_data',
dataType: 'json',
async: false,
data: JSON.stringify(get_experience_data()),
success: function (response) {
alert(response);
}
});
更新:根據此jsfiddle腳本修改get_experience_data函數
像這樣:
temp = '{ ';
temp+= '"company":"' +$(this).find('td').eq(0).html()+ '", ';
temp+= '"position":"' +$(this).find('td').eq(1).html()+ '", ';
temp+= '"datestart":"' +$(this).find('td').eq(2).html()+ '", ';
temp+= '"dateend":"' +$(this).find('td').eq(3).html()+ '", ';
temp+= '"description":"' +$(this).find('td').eq(4).html()+ '"';
temp+= ' }';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.