我有一个脚本文件,已经实现了ajax方法,它向表单添加了一条记录......然后我有一个用作后端的php文件。我想说的是我们在php中声明记录变量,我们只在jquery部分声明它。但是我们是怎么实际访问它的?使用PHP作为后端的jQuery中的Ajax方法
$record = json_decode($_POST['record']);
什么是脚本文件中的json_decode和json_stringify。
main.js
$add_form.submit(function(e) {
e.preventDefault();
var fields = ['id', 'name', 'subject', 'theory', 'practical'];
var record = {};
for (var index in fields) {
var field = fields[index];
if (field == 'id' || field == 'theory' || field == 'practical')
record[field] = parseInt($('input#add_'+field).val());
else
record[field] = $('input#add_'+field).val();
}
record.total = record.theory + record.practical;
$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxAddRecord',
record: JSON.stringify(record)
},
success: function(result) {
if ('true' == result.trim()) {
$add_modal.find('.ajax_add_result').text('Student Record Added...').css({
color: 'green',
display: 'block'
}).fadeOut(2500);
}
else {
$add_modal.find('.ajax_add_result').text('Error Adding Student Record!').css({
color: 'red',
display: 'block'
}).fadeOut(2500);
}
},
error: function() {}
});
});
action.php的
switch ($action) {
case 'ajaxAddRecord':
$record = json_decode($_POST['record']);
print ($student->addRecord($record)) ? 'true' : 'false' ;
break;
}
似乎一切都还好!你有没有得到任何错误?真正的问题是什么? –
你想让别人向你解释这段代码是如何工作的? –
是的....我想有人解释我的代码的一部分...我们在PHP中声明记录变量,我们只声明它在jQuery的一部分。但是我们是怎么实际访问它的?使用 $ record = json_decode($ _ POST ['record']); –