简体   繁体   English

Ajax加载不同的PHP页面

[英]ajax load different php pages

How can I call functions on different pages? 如何在不同页面上调用函数?

For example if I click on the start button, it will run the code necessary to start the tomcat server. 例如,如果我单击开始按钮,它将运行启动tomcat服务器所需的代码。

Here is the code for the main page: 这是主页的代码:

<input name="submit" class= "green" id ="start" type="submit" value=" Start ">
<input name="submit" id = "stop" class='red' type="submit" value=" Stop ">

Here's the second page that executes the program. 这是执行程序的第二页。

function (tomcatstart){
  $ssh->exec('service tomcat start');}

There are a couple of different approaches you can take to accomplish this sort of task. 您可以采用几种不同的方法来完成此类任务。 Here's how I would do it: 这是我的处理方式:

Firstly, I'd replace the <input> tags with <button> tags. 首先,我将<input>标记替换为<button>标记。 This is more personal preference than a real change in functionality, but since you're sending the request via AJAX, you don't need a form or inputs. 这不是真正的功能更改,而是个人喜好,但是由于您是通过AJAX发送请求的,因此不需要表单或输入。

Secondly, I'd create the JS functions to make the AJAX request, something like this: 其次,我将创建JS函数来发出AJAX请求,如下所示:

function start() {
    $.post('urlToStart.php', {
         data : 'Some data'
     }, function(returnedData) {
         //Optionally do something with the returned data, like alert 'Success' or 'Failed'
         alert(returnedData);
     });
}

Finally, you need a php page to handle the request. 最后,您需要一个php页面来处理请求。 You can either have one page that handles both the start and stop requests, or you can have different pages for each one. 您可以有一个页面处理startstop请求,也可以为每个页面使用不同的页面。

Example urlToStart.php : 示例urlToStart.php

<?php 
$data = $_POST['data'];
if($data !== null) {
    tomcatstart();
    echo "Success";
}
else {
    echo "Failed: " . print_r(error_get_last()); //Get the error message so you know what happened
}

function tomcatstart(){
  $ssh->exec('service tomcat start');
}

And that should set you on your way 那应该让你走上路

What you can do is 你能做的是

  1. Add data-task attribute, so we can write single ajax to for all 添加data-task属性,这样我们就可以为所有
  2. Add an additional class, trigger-ajax 添加一个额外的类, trigger-ajax
  3. change inputs to button or change the input type to button 将输入更改为按钮或将输入类型更改为按钮

  4. make a jquery call on click event, using class we added 使用我们添加的类对click事件进行jquery调用

     jQuery(".trigger-ajax").on('click', function(){ var _context = jQuery(this); jQuery.ajax({ url: 'ajaxrequest.php', type: "post", data:{ task: _context.attr('data-task') }, success:function(response){ console.log(response) } }) }); 
  5. handle it in php 用PHP处理

     if(!empty($_POST['task'])){ switch(trim(strtotlower($_POST['task']))){ case "start-tomcat": $ssh->exec('service tomcat start'); break; case "stop-tomcat": $ssh->exec('service tomcat stop'); break; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM