简体   繁体   English

如何通过POST提交数据对象,而不是ajax

[英]How to submit an object of data via POST, not ajax

My data looks like this, it's just an object, with two objects in it (each representing the data of a form). 我的数据看起来像这样,它只是一个对象,其中有两个对象(每个对象代表一个表单的数据)。

Object {x__sf: Object, x__mx: Object}
  x__mx: Object
    country_id: "1"
    input1: ""
    input2: ""
    ...
  x__sf: Object
    ...

I think I'll have to make a temporary form in memory and submit that? 我想我必须在记忆中制作临时表格并提交给我? I'm not sure a safe way of looping through my data and adding hidden fields to the temporary form. 我不确定循环浏览数据并将隐藏字段添加到临时表单的安全方法。 Is there a function for this? 这有功能吗? Or better way? 还是更好的方法?

I want to do this, but have it actually submit the page, because there's redirect logic serverside. 我想这样做,但让它实际提交页面,因为有重定向逻辑服务器端。

$.post('/whatever.php', data);

But what is the problem with the following approach? 但是以下方法有什么问题?

Server side: 服务器端:

<?php
// do some stuff
print "/redirect/to.php";
?>

Client side: 客户端:

$.post("/whatever.php", data, function(data) {
    location.href = data;
});

Or even more advanced: 甚至更高级:

Server side: 服务器端:

<?php
// do some stuff
header("Content-Type: application/json");
print json_encode(array(
    "success" => "/redirect/to.php"
));
?>

Client side: 客户端:

$.post("/whatever.php", data, function(data) {
    if (data.success) {
        location.href = data.success;
    }
}, "json");

Don't bother looping.... do something like this: 不要打扰循环....做这样的事情:

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

Or in you're case: 或者在你的情况下:

var data = $("#idOfForm").serialize();

You just want to stringify your data before you send it: 您只想在发送数据之前对其进行字符串化:

$.post('/whatever.php', JSON.stringify(data));

On the server side, you need to use the PHP json_decode() function: 在服务器端,您需要使用PHP json_decode()函数:

json_decode(http_get_request_body());

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

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