在 Ajax PHP MySQL 中使用全局 JavaScript 变量


use a global javascript variable in ajax php mysql

>我在本地存储中存储了一个变量'user_cache':现在我正在做一个$.getJSON调用

<script>
    user_data = JSON.parse(localStorage.getItem("user_cache"));
    $.getJSON("query.php",  { productId: productId}, function(data) { /*do something*/});
</script>

查询.php执行php_mysql数据库查询:

<? php
if( $_REQUEST["productId"] )
{
    $productid = $_REQUEST['productId'];
    /*Database connection*/
    include_once("php_includes/db_conx.php");
    $sql = "DELETE FROM USERPRODUCTCOLLECTION WHERE  Product_ID = $productid";

    if ($db_conx->query($sql) === TRUE) {
        echo "Success";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $db_conx->close();
}
?>

我的问题是我还想在查询.php文件中使用对象"user_data"来执行该数据库查询,但我不想在 $.getJSON 中传递"user_data"。是否可以在"查询.php"文件中使用"user_data"对象而无需在$.getJSON中传递它?

不幸的是,

这是不可能的。您必须将数据传递给 php 文件才能使用它。您是否倾向于传递用户数据,因为它将其作为 GET 变量(在 URL 中)传递?如果是这样,请考虑改用 jQuery.post() 调用。这样,数据将被发布,而不是在URL中。

请参阅:http://api.jquery.com/jquery.post/