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

标签 javascript php jquery ajax

在我的js文件中,我将数据数组发送到我的php文件,我想在#NAME中打印名称,在#PASSWORD中打印密码,但我在#NAME和#PASSWORD中获取名称和密码值,它类似于这个:

enter image description here

我希望它如何打印:

enter image description here

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

最佳答案

由于您为两个调用发送相同的表单,因此将其包装到 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 知道如何解析响应。

关于javascript - 如何从php返回特定数据到jquery ajax?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32378437/

相关文章:

javascript - 如何使用 require({缓存 :{ in dojo layers?

php对mysql选择行进行自然顺序排序

php artisan up 命令在 Laravel 中不起作用?

jquery - 如何使用jquery将行移动到最顶部或底部

javascript - 如何从ajax调用中获取返回值?

javascript - 我可以传递引用之类的参数吗

javascript - Webpack 试图从子目录加载 build.js

php - 您如何重写/重新编码网站以使其具有可扩展性?

javascript - $(...).tagsinput 不是函数

javascript - 在 Joomla 菜单项上创建子行