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).

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效