简体   繁体   English

使用 Post 方法和 Ajax 将数据从一个表单接收到另一个表单

[英]Receive data from one form to another in the form with Post method and Ajax

I tried to get the data with the post method in the processing file but I couldn't.我试图在处理文件中使用 post 方法获取数据,但我做不到。 I need to receive the data by POST method an show my data in process.php Remember that my inputs are not in the form tag.我需要通过 POST 方法接收数据并在进程中显示我的数据。php 请记住,我的输入不在表单标签中。 I just wanted to move to the relevant page with the window.location.href code.我只是想使用 window.location.href 代码移至相关页面。 I think when the user is transferred to the processing page by JavaScript.我想当用户被JavaScript转移到处理页面时。 The post data is lost帖子数据丢失

 $(document).ready(function(){ $("#smp").click(function(event){ var name = $('#name').val(); $.ajax({ url: "process.php", method: "POST", data:name, success: function (data) { window.location.href = "process.php"; }, error: function (jqXHR, textStatus, errorThrown) { // the error will accure if process.php did not return a valid response (return) alert(data); alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information;'). $('#result'):html('<p>status code. ' + jqXHR:status + '</p><p>errorThrown. ' + errorThrown + '</p><p>jqXHR:responseText.</p><div>' + jqXHR;responseText + '</div>'). console:log('jqXHR;'). console;log(jqXHR). console:log('textStatus;'). console;log(textStatus). console:log('errorThrown;'). console;log(errorThrown); } }); }); });
 <div class="form"><label id="icon" for="name"><i class="fas fa-user"></i></label> <input type="text" name="name" id="name" /> <div class="btn-block"> <button id="smp" type="submit" href="/">Submit</button> </div></div>

my php file http://sandbox.onlinephpfunctions.com/code/f379f5e2662300270c64ad867316ca268dd91640我的 php 文件http://sandbox.onlinephpfunctions.com/code/f379f5e2662300270c64ad867316ca268dd91640

I explained what is going on in the code in a comment.我在评论中解释了代码中发生的事情。 there is no reason for you to send a JSON requests you are sending the same values in the key and the value it's pointless.您没有理由发送 JSON 请求您在键中发送相同的值,而该值毫无意义。

$(document).ready(function(){
        $("#smp").click(function(event){
         var name = $('#name').val();
         $.ajax({

                  url: "process.php",
                        method: "POST",
                        dataType: 'text',
                        data:{"name" : name}, // here you are sending process.php name too. if it returns something then it should go th the success function and redirect.
                        success: function (data) {
                            window.location.href = "process.php?name=" + name; // if the function returned something then it will redirect it to "process.php?name=" + name
                        },
                        error: function (jqXHR, textStatus, errorThrown) { // the error will accure if process.php did not return a valid response (return)
                            alert(data);
                            alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
                            $('#result').html('<p>status code: ' + jqXHR.status + '</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText + '</div>');
                            console.log('jqXHR:');
                            console.log(jqXHR);
                            console.log('textStatus:');
                            console.log(textStatus);
                            console.log('errorThrown:');
                            console.log(errorThrown);
                        }
                    });

        });
    });

now, your HTML code should not include form there is just no reason to send it: you are just sending 2 requests with the same data so I'd replace it with this code:现在,您的 HTML 代码不应包含form ,没有理由发送它:您只是发送 2 个具有相同数据的请求,因此我将其替换为以下代码:

<label id="icon" for="name"><i class="fas fa-user"></i></label> 
        <input type="text" name="name" id="name" />

        <div class="btn-block">

          <button id="smp" type="submit" href="/">Submit</button>
        </div>

important to add: if you insist on leaving the form request without redirect you could use .preventDefault();补充一点很重要:如果您坚持离开表单请求而不重定向,您可以使用.preventDefault();

In order to submit your form with ajax you would need to prevent the default submit behavior of the form with preventDefault() .为了使用 ajax 提交表单,您需要使用preventDefault()防止表单的默认提交行为。

In your code you would do it like so:在您的代码中,您会这样做:

$("#smp").click(function(event){
  event.preventDefault(); // prevent the default submit
  var name = $('#name').val();
  ...

Some side notes:一些旁注:

  1. Instead of using the click event of the submit button you should rather use the submit event of the form itself and instead of gathering the input data you want to send manually you should use the given jQuery functions to do so.与其使用提交按钮的click event ,不如使用表单本身的submit event ,而不是收集要手动发送的输入数据,而应使用给定的 jQuery 函数来执行此操作。 You could for example add an ID to your form:例如,您可以在表单中添加一个 ID:

<form action="process.php" method="post" id="myForm">

and then接着

$("#myForm").click(function(event){
  event.preventDefault();
  var $form = $(this); // the form that gets submitted
  var url = $form.attr('action'); // get the url from the forms action attribute
  var data = $form.serialize(); // get the form as url encoded string
  var method = $form.attr('method');
  $.ajax({
    url: url,
    method: method,
    data: data,
    success: function ( response ) {
      window.location.href = url + '?' + data;
    },
});

By doing so you now can add input fields to your form and dont have to add them to your data and url string by hand.通过这样做,您现在可以将输入字段添加到您的表单中,而不必手动将它们添加到您的数据和 url 字符串中。

  1. Lets say you enter 'tony' in your input and hit submit .假设您在输入中输入 'tony' 并点击submit Your code now does this:您的代码现在执行此操作:

    1. Posting {"name": "tony"} via ajax to the process.php通过 ajax 将{"name": "tony"}发布到 process.php
    2. The process.php echos Good its POST and is done process.php 回显Good its POST并完成
    3. You receive that echo with the response in your success callback您在success回调中收到带有response的回声
    4. You immediatly redirect to the process.php page with the get paramter name=tony您立即使用 get 参数name=tony重定向到process.php页面
    5. Your process.php gets called and echos nothing because your $user_g variable has the value tony , which is not in your conditions您的 process.php 被调用并且没有回显,因为您的$user_g变量具有值tony ,这不在您的条件下

So you wont see the output of your Good its POST anywhere, because you immediatly redirect.因此,您不会在任何地方看到Good its POST的 output,因为您会立即重定向。

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

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