我需要一个帮助,即在数据库中提交后立即返回数据。我正在解释下面的代码。
addCourse.php:
<?php
$course_name=stripslashes($_POST['course_name']);
$course_short_name=stripslashes($_POST['course_short_name']);
$semester=stripslashes($_POST['semester']);
$con = mysql_connect('localhost', 'root', '******');
mysql_select_db('go_fasto', $con);
$qry ='INSERT INTO db_course (course_name,short_name,semester) values ("' . $course_name . '","' . $course_short_name . '","' . $semester . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
echo "Course has added successfully";
} else {
echo "course could not added ";
}
?>
使用ajax调用此文件,所有返回值将出现在ajax的成功函数中。我需要将提交的数据和成功消息都返回给ajax的成功函数。请帮我解决此问题。
答案 0 :(得分:1)
您可以使用json_encode
来达到预期的输出。
$result['course_name'] = $course_name;
$result['course_short_name'] = $course_short_name;
$result['semester'] = $semester;
if ($qry_res) {
$result['message'] = 'Course has added successfully';
} else {
$result['message'] = 'course could not added';
}
echo json_encode($result);
您可以检索所有提交的数据以及消息。
答案 1 :(得分:0)
在你的ajax脚本中使用下面的代码:
$.ajax({
type: 'POST',
url: ajaxURL,
data: datastring,
dataType: 'json',
success: function(data){
console.log(data);
alert(data.msg)
}
});
和PHP文件如:
<?php
$course_name=stripslashes($_POST['course_name']);
$course_short_name=stripslashes($_POST['course_short_name']);
$semester=stripslashes($_POST['semester']);
$con = mysql_connect('localhost', 'root', 'Oditek123@');
mysql_select_db('go_fasto', $con);
$qry ='INSERT INTO db_course (course_name,short_name,semester) values ("' . $course_name . '","' . $course_short_name . '","' . $semester . '")';
$qry_res = mysql_query($qry);
$result = $_POST;
if ($qry_res) {
$result['msg'] = "Course has added successfully";
} else {
$result['msg'] = "course could not added ";
}
return $result;
?>
答案 2 :(得分:0)
尝试使用:
$result['postValue'] = $_POST;
if ($qry_res) {
$result['msg'] = "Course has added successfully";
} else {
$result['msg'] = "course could not added ";
}
echo json_encode($result);
////////////////////在脚本中//////////////
$.ajax({
type: 'POST',
url: ajaxURL,
data: datastring,
success: function(data){
var data =JSON.parse(data);
console.log(data.postValue);
alert(data.msg)
}
});