我的问题是我必须在我的html表单中输入一个id,然后在按下go按钮时必须触发ajax查询,该查询从php文件中检索数据并自动填写我的html表单中的剩余输入。 我稍后将返回静态数据,我必须从数据库中检索数据。
我很擅长使用ajax jquery,因此无法解决这个问题。
HTML表单和AJAX Jquery
<html>
<head>
<title>AJAX</title>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<form>
Id:<input type="text" id="id">
Name:<input type="text" id="name">
Mobile:<input type="text" id="mob">
Email:<input type="text" id="email">
<button id="bgd">GO!</button>
</form>
<script type="text/javascript">
$("#bgd").click(function(){
$.ajax({
type: "post",
url: "im-form/phpdata.php",
dataType: "json",
data:{
id:'id',
name: 'name',
mob: 'mob',
email: 'email'
},
async: true,
cache: false,
success: function(results) {
var obj = $results;
var name = obj.name;
var mob= obj.mob;
var email= obj.email;
$("#name").val(name);
$("#mob").val(mob);
$("#email").val(email);
}
});
});
</script>
</body>
</html>
php文件
<?php
$id =5;
$name="goku";
$mob=9000;
$email="goku@dragonball.com";
$results=array('id'=>$id,'name'=>$name,'mob'=>$mob,'email'=>$email);
if($results)
{
echo json_encode($results);
}
?>
答案 0 :(得分:0)
您的代码中存在错误,
$("#bgd").click(function() {
$.ajax({
// alert("HI!"); remove this
type: "post", // use in small case
url: "im-form/phpdata.php",
dataType: "json", // dataType not datatype, check the T in camel case
data:{
id:$('#id').val(), // get input values here
name: $('#name').val(),
mob: $('#mob').val(),
email: $('#email').val()
},
//async: true,// be default it is asynchronous
cache: false,
success: function(results) {
//var obj = $.parseJSON(results); // no need to use parseJSON, as dataType is already used for it
var obj = results,
id = obj.id, // no need of [] as it is single object
name = obj.name,
mob= obj.mob,
email= obj.email;
$("#bName").val(name);
$("#blPd").val(id);
} // remove semicolon after success
});
});
PHP代码应该是,
<?php
$id =5; // use $_POST['id'] here
$name="goku"; // $_POST['name']
$mob=9000; // $_POST['mob']
$email="goku@dragonball.com"; // $_POST['email']
// make an associative array here
$results=array('id'=>$id,'name'=>$name,'mob'=>$mob,'email'=>$email);
if($results) {
echo json_encode($results);
}
?>