简体   繁体   English

POST后使用.ajax()获取表单数据

[英]Get form data after POST with .ajax()

After submitting a form via ajax, I want to get the data that I passed into the form and put it in a JS variable. 通过ajax提交表单后,我想获取传递到表单中的数据并将其放入JS变量中。

<form>
<input type="text" />
<input type="submit" value="Submit" />
</form>
$("#form").submit(function(event) {
    var form = $(this);
    $.ajax({
           type: 'POST',
           url: form.attr('action'),
           data: form.serialize(),
           success: function(data) {
               alert(data); 
           }
         });

    event.preventDefault(); // avoid to execute the actual submit of the form.
});

So how do I get the data (eg what the person posted into input) processed via POST and put it in a JS variable? 那么,如何获取通过POST处理的数据(例如,人输入的内容)并将其放入JS变量中? NOTE: I do NOT want to get the input via input.val(), It MUST be the data submitted into the databse. 注:我不想获得通过input.val输入(),它必须被提交到DATABSE数据。

In your server side code you will receive the posted data in $_POST variable.So if you want to receive it back in the response then simply post it back to the ajax request. 在服务器端代码中,您将在$_POST变量中接收发布的数据,因此,如果您想在响应中将其接收回来,只需将其发布回ajax请求即可。

Try 尝试

echo json_encode($_POST);

And also change the dataType of your ajax like this 并像这样更改您的ajax的dataType

dataType : 'json'

And in your ajax success try console.log(data) to see the response and check your browser console 在您的ajax成功中,尝试使用console.log(data)查看响应并检查您的浏览器控制台

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

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