简体   繁体   English

在页面加载时提交ajax

[英]Submitting ajax on page load

So I am submitting my AJAX just before the page is loaded and calling it on the same page like this after ajax. 所以我要在页面加载之前提交我的AJAX,并在ajax之后像这样在同一页面上调用它。

<input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>">
$(document).ready(function()
{
var store = $("#storeID").val();
$.ajax(
{
  url: '../user-style.php',
  method: 'POST',
  data: {"store":store}
});
});
<link rel="stylesheet" href="../user-style.php" media="screen" />

user-style.php 用户样式.php

if(isset($_POST['store']))
{
$stmtgetstyle = $mysqli->prepare("SELECT * FROM store_style_configuration WHERE store_id=?");
$stmtgetstyle->bind_param("i", $_GET['store']);
$stmtgetstyle->execute();
$getstyle = $stmtgetstyle->get_result();
$style = $getstyle->fetch_assoc();
$stmtgetstyle->close();
}

But user-style.php isn't getting any data neither any thing is from database is coming. 但是user-style.php不会获取任何数据,数据库中也不会有任何东西。

You'll want to pull the content of the CSS and return it. 您需要提取CSS的内容并返回它。 Now you can dynamically put it in a jQuery Object : 现在,您可以将其动态放入jQuery对象

$.ajax({
    url: '../user-style.php',
    method: 'POST',
    data: {"store":store},
    success: function(data) {
        var $cssStyles = $('<style/>');
        $cssStyles.attr('type', 'text/css');
        $cssStyles.html(data);
        $cssStyles.appendTo($('head'));
    }
});

Another method would be to pass it to the current script via the URL parameters with $_GET : 另一种方法是使用$ _GET通过URL参数将其传递到当前脚本:

<link rel="stylesheet" href="../user-style.php?store=store" media="screen" />

Or with jQuery and $_GET : 或使用jQuery$_GET

$(document).ready(function() {
    var store = $("#storeID").val();
    var $cssStyles = $('<style/>');
    $cssStyles.attr({ 'type': 'text/css', 'href': '../user-style.php?store=' + store });
    $cssStyles.appendTo($('head'));
});

You are posting your data in the ajax call, but are binding to the variable $_GET['store'] . 您正在将数据发布到ajax调用中,但绑定到变量$_GET['store'] Just change that to $_POST['store'] and it should work. 只需将其更改为$_POST['store'] This should have also sent out a notice error stating there was an undefined index 'store' in $_GET on line ... . 这也应该发出一个notice error指出undefined index 'store' in $_GET on line ...存在undefined index 'store' in $_GET on line ... This is why turning on error_reporting(E_ALL) is good when in development. 这就是为什么在开发中打开error_reporting(E_ALL)很好的原因。

Edit: actually, on second thought, it might not have thrown an error because when using a variable by reference creates a variable if it doesn't exist and doesn't throw an error. 编辑:实际上,再三考虑,它可能未引发错误,因为按引用使用变量时会创建一个变量(如果该变量不存在且不会引发错误)。 I assume this is the same for undefined array indexes. 我认为这对于未定义的数组索引是相同的。

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

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