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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染