我有一个带有表单的html文件。我想通过jQuery AJAX将表单数据发送到另一个php文件(process-registration.php)中的php类中的函数。我的问题是i)如何在AJAX请求中设置url变量?我应该在php类中包含处理请求的函数名吗?和ii)如何在php类函数中收到通过AJAx发送的表单数据? 这是html代码
<form id = "registration form">
<input type = "text" id = "name" placeholder = "Name" />
<input type = "text" id = "email" placeholder = "Email" />
<input type = "submit" id = "register" value "Register" />
</form>
//Jquery Ajax
var name = $("#name").val();
var email = $("#email").val();
var datastring = 'name='+name+'&mail='+email;
$.ajax({
//Should I add the function name to the url to look like url: "http://localhost/mySite/controllers/process-registration.php/addUser()"
type: "POST",
url: "http://localhost/mySite/controllers/process-registration.php",
data: datastring,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert("User registered successfully.");
window.location.reload(true);
}
});
//php code (process-registration.php)
<?php
require_once("../models/registrationModel.php")
class Process-registration(){
function addUser(){
//Where should I grab these values? Within the class? Outside the class? Within the function?
$name = $_POST["name"];
$email = $_POST["email"];
}
}
?>
答案 0 :(得分:0)
<form id = "registration-form">
<input type = "text" id = "name" placeholder = "Name" />
<input type = "text" id = "email" placeholder = "Email" />
<input type = "submit" id = "register" value "Register" />
</form>
Jquery Ajax
$(function(){
$("#registration-form").submit(function(){
var name = $("#name").val();
var email = $("#email").val();
var data = {"name":name, "email":email};
$.ajax({
type: "POST",
url: "http://localhost/mySite/controllers/process-registration.php",
data: data,
dataType: "json",
success: function(data){
if(data.status == "OK"){
alert(data.message)//it will give you the response message from server
alert("User registered successfully.");
window.location.reload(true);
}else{
//if error
alert("Error - "+data.message);
}
},
error: function(data){
alert("Internal server error");
}
});
});
});
php code(process-registration.php)
<?php
require_once("../models/registrationModel.php")
class Process-registration(){
function addUser(){
//Where should I grab these values? "Thats upto you"
$name = $_POST["name"];
$email = $_POST["email"];
$response = array("status"=>"OK","message"=>"Got name($name) and email($email)");
return json_encode($response);
}
}
$process-registration=new Process-registration();
echo $process-registration->addUser();
?>