根据用户的输入,我在表单的提交操作上计算了一些值。我必须将这些值保存在后端DB中。我在服务器端脚本中使用PHP。请告诉我这方面的最佳做法。它是一个单一页面应用程序,我使用.load(“Report.html”)来显示摘要页。
只需大声思考,我可以从DB、json_encode中获取行(待更新)、在jQuery中更新json对象、解码它、然后在DB中更新吗?
请帮帮我..。
我的提交按钮代码。
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});发布于 2014-01-03 04:08:29
在表单提交时,进行ajax调用,在db中设置数据库并访问json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})您还可以使用ajax的已完成回调。
yourphp.php
在db中设置值,运行所需的查询,并使用
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>发布于 2014-01-03 03:57:19
运行一些AJAX,将所需的所有信息从客户端传递到服务器端PHP (根据用例的不同,这些信息甚至可能为零)。如果需要,PHP脚本可以从数据库中获取东西,进行任何计算和/或操作,然后将信息存储回DB中。
如果需要在更新数据库后将信息返回给客户端,那么在退出JS之前,尝试从PHP脚本中返回一个JSON对象(只需以正确的格式打印代码)。
请注意,所有这些都应该异步完成,因此您需要设置AJAX回调函数,以处理从PHP脚本返回的任何信息。如果您想同步执行,那么就去做吧--但是您需要最佳实践:P
看起来您正在使用jQuery --这是关于阿贾克斯的文档
拉乌纳克·凯瑟琳的回答提供了一些相同的代码。
https://stackoverflow.com/questions/20896167
复制相似问题