使用AJAX触发PHP函数,然后在DIV上显示内容

时间:2014-05-12 01:47:42

标签: php html ajax

所以我有这样的功能,还没有完成:

function viewTestimonials(){

$sql=mysql_query("");

$msg="
    <table class=\"tftable\" border=\"1\">
        <tr><th>Testimonials</th></tr>
    ";

        while($ressult=mysql_fetch_array($sql))
        {
        $msg=$msg."
            <tr><td> </td></tr>
            <tr><td> </td></tr>
            ";
        }

$msg=$msg."
    </table>
    ";

    return $msg;
}

然后我有一个调用该函数的链接:

<a href="controls.php?control=viewTestimonial">View Testimonials</a>

所以基本上页面会重新加载,我有这样的条件来调用我的函数:

if($_GET['control']=='viewTestimonial'){
$control=viewTestimonials();
}

我的问题是:有没有办法只使用AJAX调用该函数,所以页面不需要重新加载以显示输出到div?

3 个答案:

答案 0 :(得分:0)

是的,有一种方法可以使用AJAX。但我建议使用JQuery POST

描述:使用HTTP POST请求从服务器加载数据。

所以你的代码应该是这样的:

<html>  
<head>
<script>
function viewTestimonials(){

  $.post( "controls.php", {control: viewTestimonial}, function( data ) {
      $( "#div_name" ).html( data );
    });
    }
    </script>
</head>
    <a href='#' onclick='viewTestimonials()'>View Testimonials</a>
    </html>

您需要安装JQuery。我认为w3schools的教学是正确的:http://www.w3schools.com/jquery/jquery_install.asp

答案 1 :(得分:0)

javascript:AJAX,就像问一样。

$.ajax({
      url: "some_page.php",
      type : 'POST',
      data : {control : 'hi'},
      datatype: 'json',
      success : function (resp){
          var resp = $.parseJSON(resp);
          // do stuff with resp
      },
      error: function(jqXHR, textStatus, ex) {
          console.log(textStatus + "," + ex + "," + jqXHR.responseText);
      }
});

PHP

echo json_encode($_POST);

答案 2 :(得分:0)

你不能简单地从ajax调用该函数,你可以创建一个运行你的函数的页面,你可以从ajax调用该页面并显示输出。

所以在你的页面中你可以使用这样的ajax调用。

<html>
    <body>
        <div id="myID"></div>
    </body>
</html>

<script>
    $.ajax({
       url: "getdata.php",
       context: document.body
    }).done(function(data) {
       $('#myID').html( data );
  });
</script>

对于ajax调用页面getdata.php你可以有类似的东西。

$sql=mysql_query("");

$msg="
    <table class=\"tftable\" border=\"1\">
        <tr><th>Testimonials</th></tr>
    ";

        while($ressult=mysql_fetch_array($sql))
        {
        $msg=$msg."
            <tr><td> </td></tr>
            <tr><td> </td></tr>
            ";
        }

$msg=$msg."
    </table>
    ";

   echo $msg;