繁体   English   中英

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

[英]How to return specific data from php to jquery ajax?

在我的js文件中,我正在将数据数组发送到我的php文件,我想在#NAME中打印名称,在#PASSWORD中打印密码,但是我同时在#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> 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM