简体   繁体   English

使用标题后如何将页面加载到div中

[英]How to load a page into a div after using header

I would like to know how do I load a html page into a div, after using the header into a php code. 我想知道在将标头转换成php代码后如何将html页面加载到div中。

For example: 例如:

I have the main page. 我有主页。 When I click the menu on the left side, it loads a page inside the div named "content". 当我单击左侧的菜单时,它将在div内加载一个名为“ content”的页面。 Inside the div named content, I have a form, after filling the form, I click the "Send" button. 在名为content的div内,我有一个表单,填写表单后,单击“发送”按钮。

By clicking the send button, I get redirected to my php code, which is insert_produto.php 通过单击发送按钮,我将重定向到我的php代码,即insert_produto.php。

Inside the page insert_produto.php I have the following code: 在页面insert_produto.php中,我有以下代码:

 <?php include '../logado.php'; $tipo =$_POST["tipo"]; $marca =$_POST["marca"]; $comprimento =$_POST["comprimento"]; $externo =$_POST["externo"]; $interno =$_POST["interno"]; $quantidade =$_POST["quantidade"]; //$conen tem que ser o nome da conexão, depois disso monta a query //mysqli_query($conec,"INSERT INTO produtos (tipo) VALUES ('$tipo')"); if ($quantidade == "") { $quantidade = 1; } for ($i = 1; $i <= $quantidade; $i++) { if ($externo == '' or $interno == '') { echo "Os seguintes valores são obrigatórios:</p>"; echo "• Diâmetro Externo;</p>"; echo "• Diâmetro Interno."; echo "</br></br>"; echo '<form id="erro" action="../main.php" method="post">'; echo '<input type="submit" class="botao" value="Voltar">'; echo '</form>'; die; } // se INTEIRO = primeira query, ELSE segunda query if ($comprimento == '' and $tipo == 'Inteiro'){ mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '1000', '$externo', '$interno')"); } elseif ($comprimento == '' and $tipo == 'Pedaço') { echo "Os seguintes valores são obrigatórios:</p>"; echo "• Comprimento;</p>"; echo "</br></br>"; echo '<form id="erro" action="../main.php" method="post">'; echo '<input type="submit" class="botao" value="Voltar">'; echo '</form>'; die; } else { mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '$comprimento', '$externo', '$interno')"); } } // ENCERRA O LAÇO DE REPETIÇÃO "FOR" //header("Location: " . $_SERVER["HTTP_REFERER"]); header("location: /main.php"); echo '<div class="content"> <?php include("/cadastro/produto.php"); ?> </div> ' ?> 

After the FOR , I use Header to return to the main page. FOR之后 ,我使用Header返回主页。 However, when I get to the main page, I would like to reload the previous html page inside the div called "content". 但是,当我进入主页时,我想在div内重新加载名为“ content”的上一个html页面。

I don't mind too if I have to specify manually which page I want to load inside the div, I actually prefer this way. 我也不必介意是否必须手动指定要在div中加载哪个页面,实际上我更喜欢这种方式。

In your case, you're using Location header, which change the HTTP result code to 302 Redirect , with the content you echoed after (in this case, the <div> and include of /cadastro/produto.php . All modern browsers will ignore the content received and will redirect user to Location URL. The only way to do what you want is to submit the form using AJAX and process the response. 在您的情况下,您使用的是Location标头,它将HTTP结果代码更改为302 Redirect ,并包含您回显后的内容(在本例中为<div>并包含/cadastro/produto.php 。所有现代浏览器都将忽略接收到的内容,并将用户重定向到位置 URL,要做的唯一方法是使用AJAX提交表单并处理响应。

For example, you could do it like this (using jQuery), considering you have id=form at your <form> tag: 例如,考虑到您在<form>标记处有id = form ,您可以这样进行(使用jQuery):

<script type="text/javascript">
$('#form').on ( 'submit', function ( e)
{
  e && e.preventDefault;
  $.ajax (
  {
    url: 'insert_produto.php',
    error: function ( jqXHR, textStatus, errorThrown)
    {
      alert ( 'Error sending form: ' + jqXHR.status + ' ' + jqXHR.statusText);
    },
    success: function ( data, textStatus, jqXHR)
    {
      if ( typeof ( data) == 'object' && 'result' in data)
      {
        if ( data.result == 'ok')
        {
          alert ( 'Added!');
          $('#content').load ( data.location);
        } else {
          alert ( data.message);
        }
      } else {
        alert ( 'Unknown data received.');
      }
    }
  });
});
</script>

At your PHP script, you'll need to return a JSON object with the structure: 在您的PHP脚本中,您需要返回具有以下结构的JSON对象:

{
  "result": "ok",
  "location": "\/cadastro\/produto.php"
}

And on error, with the structure: 并且在错误的情况下,具有以下结构:

{
  "result": "error",
  "message": "My error message"
}

You could do it using: 您可以使用:

 <?php include '../logado.php'; $tipo =$_POST["tipo"]; $marca =$_POST["marca"]; $comprimento =$_POST["comprimento"]; $externo =$_POST["externo"]; $interno =$_POST["interno"]; $quantidade =$_POST["quantidade"]; $return = array (); header ( "Content-Type: text/json"); //$conen tem que ser o nome da conexão, depois disso monta a query //mysqli_query($conec,"INSERT INTO produtos (tipo) VALUES ('$tipo')"); if ($quantidade == "") { $quantidade = 1; } for ($i = 1; $i <= $quantidade; $i++) { if ($externo == '' or $interno == ''){ $return["result"] = "error"; $return["message"] = "Os seguintes valores são obrigatórios:\\n• Diâmetro Externo;\\nDiâmetro Interno."; die ( json_encode ( $return); } // se INTEIRO = primeira query, ELSE segunda query if ($comprimento == '' and $tipo == 'Inteiro'){ mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '1000', '$externo', '$interno')"); } elseif ($comprimento == '' and $tipo == 'Pedaço') { $return["result"] = "error"; $return["message"] = "Os seguintes valores são obrigatórios:\\n• Comprimento."; die ( json_encode ( $return); } else { mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '$comprimento', '$externo', '$interno')"); } } // ENCERRA O LAÇO DE REPETIÇÃO "FOR" $return["result"] = "ok"; $return["location"] = "/cadastro/produto.php"; die ( json_encode ( $return); ?> 

I could not figure how to solve this issue, so i made an work-around 我不知道如何解决此问题,所以我做了一个变通办法

i'll explain how i made that work-around, so anyone facing the same issue may find it helpful 我将说明如何解决该问题,因此遇到相同问题的任何人都可能会发现有帮助

First, at the end of the php code, i simple added the following line: $_SESSION["pagina"] ="cadastro_produto"; 首先,在php代码的末尾,我简单地添加了以下行:$ _SESSION [“ pagina”] =“ cadastro_produto”;

before the: header("location: /main.php"); 之前:header(“ location:/main.php”);

then, at my main.php i did this: $teste =$_SESSION["pagina"]; 然后,在我的main.php中,我这样做了:$ teste = $ _ SESSION [“ pagina”];

and inside the div "content", i made this 在div的“内容”中,我做了这个

 <?php if ($teste == 'cadastro_produto'){ echo '<div id="caixa"> Cadastrado com sucesso.</p> voltar </div>'; //header("location: /cadastro/produto.php") } $_SESSION["pagina"] = ""; ?> 
i put $_SESSION["pagina"] = ""; 我把$ _SESSION [“ pagina”] =“”; at end, so i can set the variable teste to blank, this way an refresh of the page would not make this appear again 最后,所以我可以将变量teste设置为空白,这样刷新页面不会使它再次出现

i know this isnt the best way to fix the problem, but it worked for me and its enough for what i need 我知道这不是解决问题的最佳方法,但它对我有效,足以满足我的需求

plus i would need to figure out how to make a return message if the "insert into" was successful or not, that way i can make the return msg and echo a back button to the form 另外,如果“ insert into”成功或不成功,我将需要弄清楚如何制作返回消息,这样我就可以返回msg并在表单中回显返回按钮

this solution solves my problem, but i thank everyone who tried to help 这个解决方案解决了我的问题,但是我感谢所有尝试提供帮助的人

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

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