简体   繁体   中英

AJAX POST request with GET Parameters in URL

Can you hard code GET Variables in a AJAX POST Request?

For Example:

Javascript:

$.ajax({
    url:"/script.php?type=1"
    type: "POST"
    data:{...}
    success: function()

})

PHP:
$a = $_GET["type"]
$b = $_POST["some data"]

Why do I need this?
I would like to have one script that would run multiple tiny functions depending on the one requested. (Since I don't want my server to be clogged with files that serve only one tiny purpose)I decided to use the URL GET Variable to decide that option because I do not want to mix the information that is related to the script(the POST data) to the actual "mode" the script should run in.

If this doesn't work, would there be any similar alternative that would not involve creating loads of files?

Why not just use a POST variable when doing a POST request?
Quick lesson in making things easier ...

function ajax(type, data) {
    return $.ajax({
        url:"/script.php",
        type: "POST",
        data: $.extend(data, {type : type})
    });
}

ajax('db', {key : "value"}).done(function(data) { 
    if ( data === 'success' ) alert('insert happened!');
});
ajax('users', {user : "Bob"}).done(function(userData) {
    alert(userData);
});

and in PHP

<?php

    switch( $_POST['type'] ) {
        case "db" : 
            mysqli_query($sb, 'INSERT ' . $_POST['key'] . 'INTO SOMETHING');
            echo "success";
        break;
        case "user" : 
           echo get_user_data($_POST['user']);
        break;
        default : echo "These aren't the droids you're looking for";
    }

?>

As said in the comments, you can use php

$_SERVER['QUERY_STRING']

and eg the

parse_str()

-function to get the GET-query and parse it into an array for easy handling.

Search for 'ajax php' or think about going further using a framework for this - clientside (eg jquery or even angular), serverside for php maybe laravel, symfony or sth. to use automatisms others have developed and structured.

But: For the case u described I would agree with those who prefer submitting all your information via post (SSL) as long the data is all about sensitive 'script' information, as you said

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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