gpt4 book ai didi

php - 在 jquery .serialize() 之后如何处理 php

转载 作者:可可西里 更新时间:2023-11-01 00:36:35 27 4
gpt4 key购买 nike

好吧,不知何故,我最难弄清楚这一点,所以我想用一个表单调用 ajax,我使用 jquery 用 .serialize() 序列化它。发送到 php 的数据看起来像这样

key1=value&key2=value2&key3=value3

我正在使用 post 请求。它看起来很简单,但不知何故我很难弄清楚如何访问这些键/值对,我不能在 & 上使用 explode() 因为那会给我

[0] => key1=value1
[1] => key2=value2
[2] => key3=value3

而且我不能在 php 中使用 $_POST['key1'] 或 $_GET['key1'] 来访问这些值。我应该怎么办!!!谢谢

作为附带问题,我注意到 .serilize() 用 %0A 替换换行符,用 + 替换空格,我如何用 php 解码这些值?再次感谢!

编辑:

嘿,jquery 代码相当基础:

var formSubmit = $(this).serialize();
$.post('ajax.php',{"formSubmit": "true", "formInfo": formSubmit}

最佳答案

如果您使用 jQuery 的 Ajax 功能提交表单数据,使用 .serialize() 应该没有问题。服务器应该看到并自动 urldecode POST 内容。

作为演示,请看这段代码:

HTML

<form id="category-dynamic" class="dynamic">
<fieldset id="inner-fieldset">
<legend id="new-category">
<label for="category-name">Category Name: </label>
<input type="text" name="category-name" value="" />
</legend>
<ul id="category-fields">
<li>
<label>Field #1:</label><br />
<input type="text" name="fields[]" value="" />
</li>
<li>
<label>Field #2:</label><br />
<input type="text" name="fields[]" value="" />
</li>
</ul>
</fieldset>
</form>
<h3>POST Result</h3>
<pre></pre>

jQuery

$(document).ready(function(){
$('pre').html($('#category-dynamic').serialize());

$.post("http://jfcoder.com/test/processor.php", $('#category-dynamic').serialize(), function(data){
$('pre').html($('pre').html()+"\n\n"+data);
});
});

编辑

processor.php 文件内容:

<?php
print_r($_POST);
?>

编辑 2

我认为您的错误是您发送内容的方式使表单数据成为文本字符串而不是 url 编码的内容。

例如,您可以这样做:

var formSubmit = $(this).serialize() + "&formSubmit=true";
$.post('ajax.php', formSubmit);

而且你会得到同样的效果,服务器将能够毫无意外地扩展你的 POST 变量。

编辑 3

看这个例子:

代码在哪里:

$(document).ready(function(){
var serial = $('#category-dynamic').serialize() + "&formSubmit=true";
$('pre').html(serial);
$.post("http://jfcoder.com/test/processor.php", serial, function(data){
$('pre').html($('pre').html()+"\n\n"+data);
});
});

请注意在串行数据中添加了 "&formSubmit=true"。从 PHP 页面输出:

POST Result

category-name=&fields%5B%5D=&fields%5B%5D=&formSubmit=true

Array
(
[category-name] =>
[fields] => Array
(
[0] =>
[1] =>
)

[formSubmit] => true
)

编辑 4

这使用您描述的方法。看到区别了吗?

$(document).ready(function(){
var serial = $('#category-dynamic').serialize();
$('pre').html(serial);
$.post("http://jfcoder.com/test/processor.php", {"formSubmit":"true","serial":serial}, function(data){
$('pre').html($('pre').html()+"\n\n"+data);
});
});

输出

POST Result

category-name=&fields%5B%5D=&fields%5B%5D=

Array
(
[formSubmit] => true
[serial] => category-name=&fields%5B%5D=&fields%5B%5D=
)

关于php - 在 jquery .serialize() 之后如何处理 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6164691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com