在我的js文件中,我将数据数组发送到我的php文件,我想在#NAME中输入名称,在#PASSWORD中输入密码,但我在#NAME和#PASSWORD中获取了值名称和密码,它类似于这样:
我希望它如何打印:
$("#name").keyup(function() {
var form = $("#form").serialize();
$.ajax({
type: "POST",
url: "index.php",
data: form,
success: function(data) {
$("#NAME").html(data);
}
});
});
$("#password").keyup(function() {
var form = $("#form").serialize();
$.ajax({
type: "POST",
url: "index.php",
data: form,
success: function(data) {
$("#PASSWORD").html(data);
}
});
});

<html>
<body>
<form id="form" action="index.php" method="post">
Name :
<input type="text" name="name" id="name" /><span id="NAME">I want name here from index.php, but it returns both name and password</span>
<br/>
<br/>Password :
<input type="password" name="password" id="password" /><span id="PASSWORD">I want password here from index.php, but it returns both</span>
<br/>
<br/>
is there any other way of doing it in the same index.php file?
</form>
<script src="jquery.js"></script>
<script src="js.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:1)
由于您为两个调用发送相同的表单,因此将其更容易将其包装成1个调用并处理这两个实例并通过数组返回数据。
PHP
$arr = array();
$arr[0] = "John Doe";
$arr[1] = "password";
echo json_encode($arr);
exit();
的jQuery
$.ajax({
type: "POST",
url: "index.php",
data: form,
dataType: "json",
success: function(data) {
$("#NAME").html(data[0]);
$("#PASSWORD").html(data[1]);
}
});
请注意,您应确保在$.ajax
调用中包含dataType,以便jQuery知道如何解析响应。