douyi9447 2017-02-08 13:25
浏览 34
已采纳

使用AJAX检索特定的php变量

I started venturing on ajax and its coolness.

I managed to GET all the data from the ajax request but I wonder if you can request for a specific php variable to be retrieved.

I have the following code on HTML:

<script
              src="https://code.jquery.com/jquery-3.1.1.min.js"
              integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
              crossorigin="anonymous"></script>

<div id="textdiv">
<div id="counter"></div>
</div>
<script>
$("#textdiv").hover(function(){
    $.get('ajax.php', function(data){
            document.getElementById('counter').innerHTML = data;
            });
});
</script>

And on the ajax.php I have the following:

<?php
$kate = "Kate is here";
echo $kate;
$jack = "Jack is here";
echo $jack;
?>

Of course hovering on textdiv now I get both data however I have the following questions: 1) Is it possible to request only $jack and how would the function look like? 2) Is my code a true ajax request vs $.ajax({...

Thank you, Oliver

  • 写回答

1条回答 默认 最新

  • douangoo48863 2017-02-08 13:29
    关注

    You could do the following:

    <?php
    
    header('Content-Type: application/json; charset="utf-8"');
    
    echo json_encode([
      'kate' => "Kate is here",
      'jack' => "Jack is here",
    ]);
    

    And then use:

    $("#textdiv").hover(function(){
        $.get('ajax.php', function(data){
            document.getElementById('counter').innerHTML = data.jack;
        });
    });
    

    To answer your question in the comment: You can't.

    Javascript has no notion of the variables that exist in your php-script. Your tool of communication is a simple http request which ultimately is a simple exchange of text.

    As such the server (php script) needs to prepare that text in a way that is readable by the client (javascript).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀