簡體   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