>我正在尝试从从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 可以处理的另一个数组传递,以便我可以使用它?
还是我自己不必要地使生活复杂化?我想要的只是向服务器发送一个数组。
一个变量末尾带有 []
,它将从使用该名称传递的值创建一个数组。
例如,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()
或 .serializeArray()
,如果它们符合您的客户端序列化需求。
我对PHP不太了解,但我认为您可能忽略了一些非常简单的事情,<?--php unserialize($string) ?>
。