如果我有类似
的话<form name="myform" method="POST" action="">
<input type="text" name="mail">
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="submit">
</form>
我有一个php函数,当给出电子邮件时会返回一个带有全名的数组:
function get_fullname($email){
//some code here that gives a value to $firstname,
//$lastname, $age and $gender (for example using a cURL request)
$fullname = array(
firstname => $firstname,
lastname=>$lastname,
age=>$age,
gender=>$gender);
Return $fullname;
}
例如,如果我的地址是john.doe@gmail.com
$fullname['firstname'] = "John"
$fullname['lastname'] = "Doe"
问题是:在用户输入电子邮件地址后,如何将这些名称设为我的value
的{{1}}?
答案 0 :(得分:0)
嗯......将电子邮件发送到PHP文件:
function alterEmail(email){
$.get('getName.php',
{'email': email},
function(data){
names = data.split('.');
$('.fname').html(names[0]);
$('.lname').html(names[1]);
}
);
}
,PHP文件如下所示:
<?php
$splitEmail = explode('@',$_GET['email']);
echo $splitEmail[0];
?>
当然,只有当电子邮件看起来像john.doe@gmail.com时才会有效。您可以严格使用Javascript,但是您要求使用AJAX。
此外,要使用该Javascript函数,您可以使用onchange调用它,例如
<input type="text" onchange="alterEmail(this.value);" />
答案 1 :(得分:0)
使用jquery:
var email = $('input[name="mail"]'),
firstname = $('input[name="firstname"]'),
lastname = $('input[name="mailastnamel"]');
email.on('blur', function() {
$.ajax({
url: "ajax.php",
data: {'email': email.val()},
type: 'post',
success: function(result) {
if(result.firstname && result.lastname) {
firstname.val(result.firstname);
lastname.val(result.lastname);
}
},
dataType: 'json'
});
});
创建一个名为ajax.php的
的php文件<?php
function get_fullname($email){
//some code here that gives a value to $firstname and $lastname
$fullname = array(firstname => $firstname, lastname=>$lastname)
Return $fullname
}
if(isset($_POST['email'])) {
$fullname = get_fullname($_POST['email']);
echo json_encode($fullname);
}
?>