在我的js文件中,我正在将数据数组发送到我的php文件,我想在#NAME中打印名称,在#PASSWORD中打印密码,但是我同时在#NAME和#PASSWORD中获取值name和password,如下所示:

javascript - 如何从php返回特定数据到jquery ajax?-LMLPHP

我要如何打印:

javascript - 如何从php返回特定数据到jquery ajax?-LMLPHP



$("#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>

最佳答案

由于您要为两个调用发送相同的表单,因此将其包装为一个调用并处理两个实例并通过数组返回数据会更容易。

的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知道如何解析响应。

10-07 13:09
查看更多