我想使用AJAX在具有多个php文件中调用单个查询,但我不确定如何执行此操作。

实质上,php文件将具有三个PDO查询,这些查询将被更新,删除和添加。当前它只有更新查询。
如何将第二个查询添加到文件并获取AJAX来调用特定查询?

AJAX代码:

function updateCall() {
  var data = $('#updateForm').serialize();
  $.post('ManageCourses_DeleteSubmit.php', data, function(response){

    $("#updateForm").html(response);
    //'soft'reload parent page, after a delay to show message
    setTimeout(function(){
      $('#editModal').modal('hide')
      location.reload();
    },2000);

  }).fail(function(jqXHR, textStatus) {
    alert( "Request failed: " + textStatus );
  });
}


php文件:

<?php

include "db_conx.php";

try
{
    $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);

    $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = $db_conx->prepare("UPDATE course_details SET course_title = :course_title
        WHERE course_code = :course_code");

    $course_title = $_POST['course_title'];
    $course_code = $_POST['course_code'];

    $sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
    $sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);


    /*** execute the prepared statement ***/
    $sql->execute();

    /*** success message ***/


    $message = "<p class='text-success'> Record Successfully Updated <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
    $message = 'Message: ' .$e->getMessage();
}

die($message);
?>


有什么例子吗?

谢谢!

最佳答案

$.ajax()代码块如下所示:

$.ajax({
    type: "POST",
    url: "receiving_file.php",
    data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
    success:function(data){
        alert('This was sent back: ' + data);
    }
});


注意data:

只需使用另一个变量来确定您将调用哪个PHP例程。就像是:

data: 'myrequest=add&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,




data: 'myrequest=delete&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,


然后,在您的PHP文件中,测试该变量:

<?php
$req = $_POST['myrequest'];
if ($req == 'add'){
    //do the add
}else if ($req == 'delete'){
    //etc
}




或者,您可以使用单个$.ajax()代码块,并使用变量来确定要调用哪个PHP函数:

if (useraction=='add') {
    myreq = 'add';
}else if(useraction=='del') {
    myreq = 'delete';
}

//later on in the code...

$.ajax({
    type: "POST",
    url: "receiving_file.php",
    data: 'myrequest=' +myreq+ '&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
    success:function(data){
        alert('This was sent back: ' + data);
    }
});

09-25 18:24
查看更多