繁体   English   中英

什么时候使用ajax jquery从php文件中获取数据,是否需要在php文件中回显以返回数据?

[英]when to use ajax jquery to get data from php file, Does it need to echo in php file to return data?

什么时候使用ajax jquery从php文件中获取数据, 是否需要在php文件中回显以返回数据? 因为我想知道是否有不需要回显的情况。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
    $(function(){
      $("#btn1").click(function(){
        $.post("test2.php", 
        {
          data1: $("#txt1").val(),
          data2: $("#txt2").val()
        },
            function(resut){
              $("#div1").html(resut);
            }
          );
      });
    });
  </script>
</head>
<body>
<input type="text" id="txt1">
<input type="text" id="txt2">
<div id="div1"></div>
<input type="button" id="btn1" value="Load">

</body>
</html>

php文件test2.php

<?php

echo "You input : <u>".$_POST["data1"]."</u> and <u>".$_POST["data2"]."</u>";
?>

是的,您应该在服务器端(php)中回显/打印数据。 只有这样,客户端脚本才能获取数据。 您还可以使用JSON格式的字符串打印数据,并在客户端进行输出格式设置。

您应该使用echo json_encode($array); 在服务器端和客户端

<script>
   $.ajax({
       type : "GET",
       url : "job.php",
    }).done(function(msg) {
      var obj = jQuery.parseJSON(msg);
      alert(obj.name + " " + obj.last_name);
   });
</script>

暂无
暂无

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

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