如何使用ajax从js调用php函数?

时间:2015-08-02 13:20:40

标签: javascript php jquery ajax

我有js函数在我做某事时触发,我想调用一个php函数。我知道我需要使用ajax这样做,但我怎么能这样做呢?我学习ajax,但我没有找到它的参考。你能告诉我它的工作原理吗?这是我希望它如何工作的基础:

JS:call php function when JS triggered.

PHP:echo(or do) something.
编辑:我想要获得的是无限滚动,当我到达页面底部时,它会给我新的php数据。我关注this一集,我想要蓝色方块,以显示数据。 这是剧集的代码。当页面到底部时显示蓝色方块

 <!DOCTYPE html>
    <html>
    <head>
    <script>
    function yHandler(){
        // Watch video for line by line explanation of the code
        // http://www.youtube.com/watch?v=eziREnZPml4
        var wrap = document.getElementById('wrap');
        var contentHeight = wrap.offsetHeight;
        var yOffset = window.pageYOffset; 
        var y = yOffset + window.innerHeight;
        if(y >= contentHeight){
            // Ajax call to get more dynamic data goes here
            wrap.innerHTML += '<div class="newData"></div>';
        }
        var status = document.getElementById('status');
        status.innerHTML = contentHeight+" | "+y;
    }
    window.onscroll = yHandler;
    </script>
    <style>
    div#status{position:fixed; font-size:24px;}
    div#wrap{width:800px; margin:0px auto;}
    div.newData{height:1000px; background:#09F; margin:10px 0px;}
    </style>
    </head>
    <body>
    <div id="status">0 | 0</div>
    <div id="wrap"><img src="temp9.jpg"></div>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="fooid">click me!</div>
<script>
$( "#fooid" ).click(function() {
   var term = "some string foo";
  // Send the data using post, in PHP you will get $_POST['foo']
  var posting = $.post('index.php', { foo: term } );
  // alert the results (in php script: echo "test performed!";)
  posting.done(function( data ) {
   alert( "Data Loaded: " + data );
  });
});
</script>

</body>
</html>