如何使用AJAX使用<li> onclick事件调用php函数?

时间:2016-01-28 15:52:24

标签: javascript php jquery ajax

如果我使用onclick事件,你能帮助我如何使用AJAX调用PHP函数(调用外部服务器)吗?

<div class="container">
<h3 style=color:blue;>INFORMATION </h3>
<ul class="nav nav-pills" style="background-color:lightblue" >
<li class="dropdown">
  <a class="dropdown-toggle" data-toggle="dropdown" href="#"   style=color:blue;> Information <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a onclick="get_inf1()" style="color:blue;cursor:pointer;">Submenu_1</a></li> 
    <li><a onclick="get_inf2()" style="color:blue;cursor:pointer;">Submenu_2</a></li> 
    <li><a onclick="get_inf3()" style="color:blue;cursor:pointer;">Submenu_3</a></li> 
  </ul>
</li>
</ul>
</div>

所谓的php函数的开始代码是:

<?php 
function get_info1()
{
    $bdy = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $bdy.= "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
    xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    $bdy.= "<soap:Body>";
    $bdy.= "<GetInformation xmlns=\"http:// website  /\" />";
    $bdy.= "</soap:Body>";
    $bdy.= "</soap:Envelope>\r\n";
    $req = "POST /data.asmx HTTP/1.1\r\n";
等等......

1 个答案:

答案 0 :(得分:0)

使用example.php:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container">
<h3 style=color:blue;>INFORMATION </h3>
<ul class="nav nav-pills" style="background-color:lightblue" >
<li class="dropdown">
  <a class="dropdown-toggle" data-toggle="dropdown" href="#"   style=color:blue;> Information <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li id="uniqueId01">Submenu_1</li> 
        <li id="uniqueId02">Submenu_2</li> 
        <li id="uniqueId03">Submenu_3</li> 
    </ul>
</li>
</ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$('.dropdown-menu li').on('click', function(){
    $.get('/path/to/script.php', { menu: this.id }, function(data){
        $('body').append(data); //do something with whatever data is returned
    });
});
</script>
</body>
</html>

路径/到/ script.php的:

<?php

switch($_GET['menu']){

    case 'uniqueId01':
        menu1();
        break;
    case 'uniqueId02':
        menu2();
        break;
    case 'uniqueId03':
        menu3();
        break;
    default:
        someDefaultFunction();
        break;
}

function menu1(){
    echo 'You clicked Menu 1! '; //do something
}
function menu2(){
    echo 'You clicked Menu 2! ';
}
function menu3(){
    echo 'You clicked Menu 3! ';
}