2

我正在尝试从我从 JQuery Ajax 调用发送到服务器中的 PHP 脚本的 URL 反序列化一个数组。

我做了什么

我一直以这种方式使用 jQuery Ajax 成功地将带有值的变量发送到服务器:

// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();

然后我以这种方式准备要通过 Ajax 发送的数据:

var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString

并像这样使用 jQuery Ajax 发送它:

$.ajax({
        url: "script.php",
        type: "GET",
        data: data,
        cache: false,
        dataType:'html',
        success: function (html) {
            // Do something successful
        }
});

然后我以这种方式在服务器中获取它:

$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;

而且我可以根据需要轻松使用我的变量。但是,我需要使用数组来执行此操作。

主要问题

读了很多,我已经学会了将数组发送到服务器的专业方法:序列化它!我已经学会了用 jQuery 做这件事的方法:

var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
   array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo

这似乎是对的。我像以前一样将其添加到数据中:

var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo

如何在服务器中重建(反序列化)我的阵列?我已经尝试过和以前一样的方法:

$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;

没有成功!任何想法为什么?如何让我的序列化数组以这种方式在服务器中作为 PHP 可以处理的另一个数组传递,以便我可以使用它?

还是我不必要地让自己的生活复杂化了?我想要的只是将一个数组发送到服务器。

4

2 回答 2

1

I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

于 2012-06-19T03:46:28.863 回答
1

如果您在变量[]的末尾命名一个变量,它将根据使用该名称传递的值创建一个数组。

例如,http://www.example.com/?data[]=hello&data[]=world&data[]=test, 将导致$_GET["data"] == array('hello', 'world', 'test');在 PHP 中创建数组。

同样的,你可以在 PHP 中创建一个关联数组:http://www.example.com/?data[first]=foo&data[second]=bar将导致$_GET["data"] == array("first" => "foo", "second" => "bar");

顺便说一句,您可能对使用 jQuery.serialize()或jQuery 感兴趣.serializeArray(),如果它们适合您的客户端序列化需求。

于 2012-06-19T00:17:22.470 回答