简体   繁体   English

在提交时使用jquery .post将javascript数组传递到服务器,然后在PHP中打印数组?

[英]Pass javascript array to server using jquery .post on submit and then print array in PHP?

HTML: HTML:

<form id="continue" action="summary.php" method="post">
<input type="submit" value="Continue" >
</form>

JS/JQuery JS / jQuery

$('#continue').submit(function(){
    var data = ["jon", "steve"];
    var nameArray = JSON.stringify(data);
    $.post("summary.php", { nameArray: nameArray });
});

PHP 的PHP

$name = json_decode($_POST["nameArray"]);
print_r($name);

When I click the "Continue" button, I want to be redirected to the summary.php page and list the names. 当我单击“继续”按钮时,我想重定向到summary.php页面并列出名称。 Currently, I get an "Undefined index: nameArray error when the summary.php page is loaded. 当前,当加载summary.php页面时,出现“未定义索引:nameArray错误”。

I checked firebug and there is no POST. 我检查了萤火虫,没有开机自检。 So it looks like nameArray isn't even being posted either. 因此,似乎nameArray甚至都没有发布。 What's the solution? 有什么解决方案?

This is not the correct way of handling data. 这不是处理数据的正确方法。

You are posting a page (leaving it) and doing an ajax post within? 您正在发布页面(保留页面)并在其中进行ajax发布? If you want to stay on the page, you use an ajax post. 如果要保留在页面上,请使用ajax帖子。 If you are posting data normally, you use a form post. 如果您正常发布数据,则使用表单发布。

If you want to post the name jon or steve as an array you can use the following html 如果要发布名称jon或steve作为数组,则可以使用以下html

<input type="hidden" name="nameArray[]" value="jon" />
<input type="hidden" name="nameArray[]" value="steve" />

If you want to use ajax, then just dont do it on the submit of a form. 如果要使用ajax,则不要在提交表单时使用。 You can do it on a submit, but then return false at the end of the function so the page will not be submitted (you will stay on the current page) 您可以在提交时执行此操作,但在函数末尾返回false,因此将不提交页面(您将停留在当前页面上)

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

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