简体   繁体   English

URL 中带有 GET 参数的 AJAX POST 请求

[英]AJAX POST request with GET Parameters in URL

Can you hard code GET Variables in a AJAX POST Request?你能在 AJAX POST 请求中硬编码 GET 变量吗?

For Example:例如:

Javascript: 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. (因为我不希望我的服务器被只用于一个小目的的文件堵塞)我决定使用 URL GET 变量来决定该选项,因为我不想混合与脚本相关的信息( POST 数据)到脚本应该运行的实际“模式”。

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?为什么在执行 POST 请求时不使用 POST 变量?
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 中

<?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正如评论中所说,您可以使用 php

$_SERVER['QUERY_STRING']

and eg the例如

parse_str()

-function to get the GET-query and parse it into an array for easy handling. -function 获取 GET-query 并将其解析为数组以便于处理。

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.搜索“ajax php”或考虑使用一个框架来进一步发展 - 客户端(例如 jquery 甚至 angular),php 的服务器端可能是 laravel、symfony 或 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但是:对于你描述的情况,我同意那些喜欢通过邮寄(SSL)提交所有信息的人,只要数据都是关于敏感的“脚本”信息,正如你所说

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

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